在一个Android项目的Java code,如果你想为一个视图的资源,你可以做类似的参考:
查看Add按钮= findViewById(R.id.button_0);
在上面R.id.button_0不是一个字符串。是否可以动态地引用资源由字符串,如 R.id.button_0
我想用指一个按钮, R.id.button_%I
,其中%I
被替换为一些有效的索引。
则getIdentifier INT渣油= getResources()。(button_%I,
ID,getPackageName());
查看Add按钮= findViewById(渣油);
其中,%I
替换一些有效的索引。
在 getResources()
方法属于上下文
类,所以您可以使用直接从活动
。如果你不是一个活动里面,然后用一个上下文的访问:( myCtxt.getResources()
)
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);
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
"?
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);
where %i
is replaced by some valid index.
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()
).
相关推荐
最新文章