Android和获取ID为投视图,作为字符串 [英] Android and getting a view with id cast as a string

查看:123
本文介绍了Android和获取ID为投视图,作为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个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()).

这篇关于Android和获取ID为投视图,作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆