[英]Android and getting a view with id cast as a string
In the Java code of an Android project if you want the reference for a view resource you can do something like: 在Android项目的Java代码中,如果您想要视图资源的引用,您可以执行以下操作:
View addButton = findViewById(R.id.button_0);
In the above R.id.button_0 is not a String. 在上面的R.id.button_0不是String。 Is it possible to dynamically refer to a resource by a string, such as " R.id.button_0
"? 是否可以通过字符串动态引用资源,例如“ R.id.button_0
”?
I'd like to refer to a button by " R.id.button_%i
" where %i
is replaced by some valid index. 我想通过“ R.id.button_%i
”来引用一个按钮,其中%i
被一些有效索引替换。
int resID = getResources().getIdentifier("button_%i",
"id", getPackageName());
View addButton = findViewById(resID);
where %i
is replaced by some valid index. 其中%i
被一些有效索引替换。
The getResources()
method belongs to the Context
class, so you can use that directly from an Activity
. getResources()
方法属于Context
类,因此您可以直接从Activity
使用它。 If you are not inside an activity, then use a context to access: ( myCtxt.getResources()
). 如果您不在活动中,则使用上下文访问:( myCtxt.getResources()
)。
您可以尝试将所需的所有ID放入数组中,然后使用该数组动态引用您的资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.