为什么我的按钮视图id在运行时发生更改



我正试图在Kotlin中编写一个简单的Android应用程序,它可以更改不同视图的颜色。

我有以下代码来初始化视图和单击侦听器(当然前面的private lateinit声明(:

private fun setListeners()
{
boxOneText = findViewById(R.id.box_one_text)
boxTwoText = findViewById(R.id.box_two_text)
boxThreeText = findViewById(R.id.box_three_text)
boxFourText = findViewById(R.id.box_four_text)
boxFiveText = findViewById(R.id.box_five_text)
btnRed = findViewById(R.id.button_red)
btnYellow = findViewById(R.id.button_yellow)
btnBlue = findViewById(R.id.button_blue)
val rootLayout = findViewById<View>(R.id.constraint_layout)
// Set click listener for all text views
val views = listOf<View>(boxOneText, boxTwoText, boxThreeText, boxFourText, boxFiveText, rootLayout)
views.map { view -> view.setOnClickListener { makeColored(it) } }
// Set click listener for all buttons
val buttons = listOf(btnRed, btnYellow, btnBlue)
buttons.map { button -> button.setOnClickListener { makeSpecificColor(it, views) } }
}

设置单个TextViews的颜色的代码看起来是这样的,并且有效(忽略box_two的lockdown_earth条目,我在玩一些东西(:

private fun makeColored(view: View)
{
when(view.id)
{
R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
R.id.box_two_text -> view.setBackgroundResource(R.drawable.lockdown_earth)
R.id.box_three_text -> view.setBackgroundColor(Color.BLUE)
R.id.box_four_text -> view.setBackgroundColor(Color.MAGENTA)
R.id.box_five_text -> view.setBackgroundColor(Color.BLUE)
else -> view.setBackgroundColor(Color.LTGRAY)
}
}

但是,以下更改所有文本视图(包括rootLayout(颜色的代码不起作用:

// In this context, view is a Button
private fun makeSpecificColor(view: View, views: List<View>)
{
// TODO For some reason the id doesn't match??
val color = when(view.id)
{
R.id.button_yellow -> R.color.my_yellow
R.id.button_red -> R.color.my_red
R.id.button_blue -> R.color.my_blue
else -> R.color.colorPrimary
}
views.map { it.setBackgroundColor(color) }
}

正如我的TODO所暗示的,由于某种原因,视图id是NOT在触发clickListener之前的id,并且总是输入'else'。我在调试模式下运行了这个,但传递的ID与我在整个应用程序中的任何视图都不匹配。是否以某种方式分配了新的ID?如果是这样,为什么TextViews与它们的监听器一起工作?

是因为我使用了按钮列表上的地图吗?我一直有点盲目地用它来代替for循环。

问题是我使用了错误的方法来设置背景色。我需要使用CCD_ 2而不是使用setBackgroundColor()

不幸的是,调试器没有正确解析资源ID,因为它让我陷入了试图解决错误问题的困境。

最新更新