首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将包含id的字符串转换为id类型Int

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

Stack Overflow用户
提问于 2021-03-01 04:48:54
回答 2查看 41关注 0票数 0

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

代码语言:javascript
运行
AI代码解释
复制
val stringContainingId = "R.id.testBtn"

并且在activity中将i testBtn设置为id

_

main:

代码语言:javascript
运行
AI代码解释
复制
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?
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-03-01 05:21:02

在Android Java框架中,android.R.id.testBtn是一个按钮的标识符。您可以在框架的许多布局中找到它(请选择

_

对话框

_

项,选择

_

对话框

_

singlechoice,简单

_

下拉列表

_

项目

_

1行等)。在Android框架xml中,它由@+id/testBtn表示

伙计,你得到id =0是因为

不是字符串。它实际上是一个

变量。如果你想获得标识符,你只需要添加

找到它。

代码语言:javascript
运行
AI代码解释
复制
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

票数 1
EN

Stack Overflow用户

发布于 2021-03-01 05:26:18

使用just

,not

..。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66416793

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档