将包含id的字符串转换为id类型Int



我有一个包含按钮id的字符串:

val stringContainingId = "R.id.testBtn"

并且testBtn被设置为activity_main:

中的id
<Button
android:id="@+id/testBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

所以,我想在我的MainActivity中设置这个按钮的文本。stringContainingId是一个字符串,所以我必须转换为Int类型的id:

val id: Int = applicationContext.resources.getIdentifier("R.id.testBtn", "id", applicationContext.packageName)

然后更改testBtn:

的文本
val testBtn = findViewById<Button>(id)
testBtn.text = "Other text"

但是在运行时应用程序崩溃,并显示这个错误:

testBtn must not be null

但如果换成findViewById<Button>(R.id.testBtn),一切都很顺利。

从字符串中获取id的变量'id'有什么问题?

在Android Java框架中,Android . r.id . testbtn是一个Button的标识符。您可以在框架的许多布局中找到它(select_dialog_item、select_dialog_singlechoice、simple_dropdown_item_1line等)。在Android框架xml中,表示为@+id/testBtn

Mate,你得到id = 0,因为R.id.testBtn不是字符串。它实际上是一个int变量。如果您想获得标识符,只需添加testBtn即可找到它。

val id: Int = applicationContext.resources.getIdentifier(testBtn, "id", applicationContext.packageName)

阅读更多文档官方android,我相信你知道的更多。

e。g: https://www.codota.com/code/java/methods/android.content.res.Resources/getIdentifier

什么是"android.R.id.text1"?

https://developer.android.com/reference/kotlin/android/R.id

getIdentifier()中只使用“testBtn”,不使用“R.id.testBtn”

最新更新