正如您在阅读本文时所意识到的,我是编程新手,而且非常拘泥。
我在布局中有5个文本视图,ID为";box_one_text、box_two_text"依此类推,当我尝试在MainActivity上设置点击侦听器时,我会创建一个项目列表,调用每个textView的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) }
}
}
listOf中的所有内容都是一个错误,调用";未解析引用";我之前说过(
我该如何解决这个问题?
我也遇到了这个问题,最终在这里找到了答案:https://github.com/udacity/andfun-kotlin-color-my-views/issues/11
这是因为我们的代码中缺少视图绑定;要解决这个问题,有两种解决方案。
简单的方法是将以下行添加到应用程序级Gradle文件:
id 'kotlin-android-extensions'
另一种解决方案是遵循此处讨论的数据绑定步骤:https://classroom.udacity.com/courses/ud9012/lessons/4f6d781c-3803-4cb9-b08b-8b5bcc318d1c/concepts/68b85cff-8813-496b-86ba-57ed352d8bcf.我不确定你是否和我学习的是同一门课程,但我链接的课程是免费的,它的代码练习与你的类似(很可能相同(。
我在上面提到的GitHub URL中还有其他一些想法。
box_one_text, box_two_text, box_three_text, box_four_text, box_five_text, constraint_layout
不直接引用视图,它们只是IDs
使用findViewById
查找所需视图,然后设置OnClickListener
尝试以下
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) }
}