Android Studio 4.1 xml 问题(求助)
Android Studio 4.1 xml problem (plz help)
我正在尝试在我的 MainActivity.kt 中使用按钮和图像,但是不知何故,当我在 activity_main.xml 中给它们一个 id 时,正如您在下面的代码中看到的那样:
<Button
android:id="@+id/firstbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
当我尝试在 MainActivity.kt 中使用它们时,它根本无法识别它们!编辑器的自动导入已开启,但例如,如果我在 MainActivity.kt 中键入 "firstbtn",则不会自动完成,并且会出现错误:“未解析的引用:firstbtn”出现。
如果你知道我该如何解决,请帮助,我真的被困住了!
在MainActivity.kt的onCreate函数中输入
val firstbtn = findViewById<Button>(R.id.firstbtn)
或者,如果以后不需要引用,请使用作用域函数,例如 apply,如下所示:
findViewById<Button>(R.id.firstbtn).apply{
//configure firstbtn for your needs
}
另一种解决方案是使用扩展插件。将它添加到您的模块 build.gradle 文件:
plugins {
id 'kotlin-android-extensions'
[...]
}
在你的activity中导入包
import kotlinx.android.synthetic.main.activity_main.*
然后您可以像您最初想要的那样使用视图(只需输入视图的 ID,例如 firstbtn)。
我正在尝试在我的 MainActivity.kt 中使用按钮和图像,但是不知何故,当我在 activity_main.xml 中给它们一个 id 时,正如您在下面的代码中看到的那样:
<Button
android:id="@+id/firstbtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hi!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
当我尝试在 MainActivity.kt 中使用它们时,它根本无法识别它们!编辑器的自动导入已开启,但例如,如果我在 MainActivity.kt 中键入 "firstbtn",则不会自动完成,并且会出现错误:“未解析的引用:firstbtn”出现。 如果你知道我该如何解决,请帮助,我真的被困住了!
在MainActivity.kt的onCreate函数中输入
val firstbtn = findViewById<Button>(R.id.firstbtn)
或者,如果以后不需要引用,请使用作用域函数,例如 apply,如下所示:
findViewById<Button>(R.id.firstbtn).apply{
//configure firstbtn for your needs
}
另一种解决方案是使用扩展插件。将它添加到您的模块 build.gradle 文件:
plugins {
id 'kotlin-android-extensions'
[...]
}
在你的activity中导入包
import kotlinx.android.synthetic.main.activity_main.*
然后您可以像您最初想要的那样使用视图(只需输入视图的 ID,例如 firstbtn)。