我有一个包含按钮id的字符串:
val stringContainingId = "R.id.testBtn"
并且在activity中将i testBtn设置为id
_
main:
So, I want to set the text of this button in my MainActivity. stringContainingId is a string, so I have to convert to id with type Int:
val id: Int = applicationContext.resources.getIdentifier("R.id.testBtn", "id", applicationContext.packageName)
Then changing the text of testBtn:
val testBtn = findViewById(id)
testBtn.text = "Other text"
But at runtime app crashes, and shows this error:
testBtn must not be null
But if changed to findViewById(R.id.testBtn), eveything goes smoothly.
What's wrong with variable 'id' that is getting the id from string?
发布于 2021-03-01 05:21:02
在Android Java框架中,android.R.id.testBtn是一个按钮的标识符。您可以在框架的许多布局中找到它(请选择
_
对话框
_
项,选择
_
对话框
_
singlechoice,简单
_
下拉列表
_
项目
_
1行等)。在Android框架xml中,它由@+id/testBtn表示
伙计,你得到id =0是因为
不是字符串。它实际上是一个
变量。如果你想获得标识符,你只需要添加
找到它。
val id: Int = applicationContext.resources.getIdentifier(testBtn, "id", applicationContext.packageName)
在官方安卓文档中阅读更多,我相信你会知道更多。
例如:
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
发布于 2021-03-01 05:26:18
使用just
,not
在
..。
https://stackoverflow.com/questions/66416793
复制