Android 并获取带有 id 的视图作为字符串 [英] Android and getting a view with id cast as a string
问题描述
在 Android 项目的 Java 代码中,如果您想要视图资源的引用,您可以执行以下操作:
In the Java code of an Android project if you want the reference for a view resource you can do something like:
View addButton = findViewById(R.id.button_0);
在上面的 R.id.button_0 不是字符串.是否可以通过字符串动态引用资源,例如R.id.button_0
"?
In the above R.id.button_0 is not a String. Is it possible to dynamically refer to a resource by a string, such as "R.id.button_0
"?
我想用R.id.button_%i
"来引用一个按钮,其中%i
被一些有效的索引替换.
I'd like to refer to a button by "R.id.button_%i
" where %i
is replaced by some valid index.
推荐答案
int resID = getResources().getIdentifier("button_%i",
"id", getPackageName());
View addButton = findViewById(resID);
其中 %i
被一些有效索引替换.
where %i
is replaced by some valid index.
getResources()
方法属于 Context
类,因此您可以直接从 Activity
使用它.如果您不在活动中,则使用上下文访问:(myCtxt.getResources()
).
The getResources()
method belongs to the Context
class, so you can use that directly from an Activity
. If you are not inside an activity, then use a context to access: (myCtxt.getResources()
).
这篇关于Android 并获取带有 id 的视图作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!