Home > Mobile >  How to reference view objects inside a list?
How to reference view objects inside a list?

Time:08-19

I'm trying to create a method to set a listener to each of my views inside a list like:

    private fun setListeners() {

    val clickableViews: List<View> =
        listOf(box_one_text, box_two_text, box_three_text,
    box_four_text, box_five_text)

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

box_one_text, box_two_text and so on are the id of the views inside my xml file and I'm trying to set a color of it when they are clicked like:

   fun makeColored(view: View) {
    when (view.id) {

        // Boxes using Color class colors for background
        R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
        R.id.box_two_text -> view.setBackgroundColor(Color.GRAY)

        // Boxes using Android color resources for background
        R.id.box_three_text -> view.setBackgroundResource(android.R.color.holo_green_light)
        R.id.box_four_text -> view.setBackgroundResource(android.R.color.holo_green_dark)
        R.id.box_five_text -> view.setBackgroundResource(android.R.color.holo_green_light)

        else -> view.setBackgroundColor(Color.LTGRAY)
    }
}

the problems is that all of the elements inside the list are all red lines or can't reference by the list

CodePudding user response:

First thing first, the list type is wrong. You said that box_one_text and box_two_text are the view id. View id type is Int, so you should change the list to list of Int

val clickableViews: List<Int> =
    listOf(box_one_text, box_two_text, box_three_text,
box_four_text, box_five_text)

Then, to apply a click listener to each of the id, you need to find the view using findViewById

for(item in clickableViews){
    findViewById<View>(item).setOnClickListener{makeColored(it)}
}

Or if you use view binding, you can follow below code:

val clickableViews: List<View> =
    listOf(binding.boxOneText, binding.boxTwoText, binding.boxThreeText,
binding.boxFourText, binding.boxFiveText)
for(item in clickableViews){
    item.setOnClickListener{makeColored(it)}
}

CodePudding user response:

Try this:

private fun setListeners() {

    val clickableViews: List<Int> =
        listOf(R.id.box_one_text, R.id.box_two_text, R.id.box_three_text,
    R.id.box_four_text, R.id.box_five_text)
    
    for(item in clickableViews){
        findViewById<View>(item).setOnClickListener{makeColored(it)}
    }

}
  • Related