如何引用列表中的视图对象



我正在尝试创建一个方法,将listener设置为列表中的每个views,如:

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_textbox_two_text等是我的xml文件中视图的id,我试图在单击它们时设置它的颜色,例如:

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)
}
}

问题是list中的所有元素都是红线,或者不能被列表引用

首先,列表类型是错误的。你说box_one_textbox_two_text是视图id。视图id类型是Int,所以你应该将列表更改为Int的列表

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

然后,要将单击侦听器应用于每个id,您需要使用findViewById查找视图

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

或者,如果您使用视图绑定,您可以遵循以下代码:

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

试试这个:

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)}
}
}

最新更新