Error "Unresolved reference" when listing Views from XML file

Viewed 748

As you will realise while reading this, I am new to programming, and I am very much stuck.

I have 5 text views in the layout with ID´s "box_one_text , box_two_text" and so on, when I try to set the click listeners on MainActivity, I create a list of items calling for each textView by it's ID:

private fun setListeners(){
    val clickableViews: List<View> =
        listOf(box_one_text, box_two_text, box_three_text, box_four_text,
        box_five_text, constraint_layout)

    for(item in clickableViews){
        item.setOnClickListener { makeColored(it)  }
    }
}

Everything inside listOf is an error, calling for the "Unresolved reference" I talked about earlier)

How do I fix this?

2 Answers

I also came across this issue and finally found the answer here: https://github.com/udacity/andfun-kotlin-color-my-views/issues/11

This is because view binding is missing from our code; to solve this problem, there are 2 solutions.

The simple way is to add the below line to app level Gradle file:

id 'kotlin-android-extensions'

The other solution is to follow the data binding steps which is discussed here: https://classroom.udacity.com/courses/ud9012/lessons/4f6d781c-3803-4cb9-b08b-8b5bcc318d1c/concepts/68b85cff-8813-496b-86ba-57ed352d8bcf. I'm not sure if you're following the same course as me, but the course I linked is free and it has a similar (highly likely the same) code exercise as yours.

There are some other ideas from the GitHub URL I included above.

box_one_text, box_two_text, box_three_text, box_four_text, box_five_text, constraint_layout dont refer to the views directly instead they are just the IDs Use findViewById to find the required view and later set OnClickListener

Try the following

val view1 : View = findViewById(R.id.box_one_text)
val view2 : View = findViewById(R.id.box_two_tex)

//pattern follows for the rest of the views too

    val clickableViews: List<View> =
        listOf(view1, view2, view3 ....)

    for(item in clickableViews){
        item.setOnClickListener { makeColored(it)  }
    }

Related