Android和获取ID为投视图,作为字符串视图、字符串、Android、ID

由网友(非我良者怎知我心)分享简介:在一个Android项目的Java code,如果你想为一个视图的资源,你可以做类似的参考:查看Add按钮= findViewById(R.id.button_0);在上面R.id.button_0不是一个字符串。是否可以动态地引用资源由字符串,如 R.id.button_0 我想用指一个按钮, R.id.button...

在一个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(渣油);
 
android开发,UI布局问题,eclipse中不显示XML的预览视图

其中,%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()).

阅读全文

相关推荐

最新文章