【发布时间】:2021-03-10 10:42:01
【问题描述】:
我正在尝试运行第 5 章“傻瓜式 Android 应用程序开发一体化”中的代码。
书中的代码直接引用了onButtonClick函数中的view Id
fun onButtonClick(view: View){
...
if (checkBox.isChecked()){
...
}
但 Android Studio 将复选框突出显示为未解析的引用。
我尝试了什么
我尝试改变
fun onButtonClick(view: View){
...
val checkBox = view.findViewById<CheckBox>(R.id.checkBox)
if (checkBox.isChecked()){
...
}
但是在运行时使用 checkBox 崩溃是空的。 我看了How can you add a reference to another view through attributes in android? 并尝试更改
fun onButtonClick(view: View){
...
val vp : ViewGroup = view.getParent()
val checkBox = vp.findViewById<CheckBox>(R.id.checkBox)
if (checkBox.isChecked()){
...
}
但是类型不匹配:推断类型是 ViewParent(没有 findViewByID)
【问题讨论】:
-
如果你在一个片段/活动中,只需使用 findViewById
-
The code in the book refers directly to view Id's in an onButtonClick function见我上面提供的链接。合成导入已被弃用,新项目不再具有导入
标签: android