Java Android:从ArrayList设置资源字符串ID?
我相信有更好的方法可以做到这一点,但我对编程完全是新手,所以我为自己的无知提前道歉 我的问题是: 我在strings.xml中有一个用字符串的名称参数填充的ArrayList,我试图用.setText()填充一个TextView,它利用从数组的一部分动态创建的资源ID。例如Java Android:从ArrayList设置资源字符串ID?,java,android,string,resources,Java,Android,String,Resources,我相信有更好的方法可以做到这一点,但我对编程完全是新手,所以我为自己的无知提前道歉 我的问题是: 我在strings.xml中有一个用字符串的名称参数填充的ArrayList,我试图用.setText()填充一个TextView,它利用从数组的一部分动态创建的资源ID。例如 ArrayList<String> options = new ArrayList<String>(); options.add("bacon"); options.add("ham"); //R.
ArrayList<String> options = new ArrayList<String>();
options.add("bacon");
options.add("ham");
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option1.setText(R.string.(options.get(0)));
ArrayList options=new ArrayList();
期权。添加(“培根”);
选项。添加(“火腿”);
//R.id.option1在我的布局中,R.string.bacon在my strings.xml中
TextView选项1=(TextView)findViewById(R.id.option1);
option1.setText(R.string.(options.get(0));
这显然不是我的完整代码。这只是同一问题面临的一个例子
有什么想法吗
提前谢谢 听起来您想按名称查找资源id,以便在需要整数id的调用中使用它(例如在findViewById()中): 返回给定资源名称的资源标识符。完全限定的资源名称的形式为“包:类型/条目”。如果此处分别指定了defType和defPackage,则前两个组件(package和type)是可选的。 注意:不鼓励使用此功能。按标识符检索资源比按名称检索资源要高效得多 示例: 或
作为一种想法,您可以使用资源ID的int数组,而不是名称的字符串数组:
ArrayList<Integer> options = new ArrayList<Integer>();
options.add(R.string.bacon);
options.add(R.string.ham);
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option1.setText(options.get(0));
ArrayList options=new ArrayList();
options.add(R.string.bacon);
options.add(R.string.ham);
//R.id.option1在我的布局中,R.string.bacon在my strings.xml中
TextView选项1=(TextView)findViewById(R.id.option1);
option1.setText(options.get(0));
多么简单的解决方案。非常感谢@杰瑞德-很乐意帮忙@特德·霍普的想法是一个值得考虑的好想法。
String name = "bacon";
int id = resources.getIdentifier(name, "string", "com.package");
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+name+"' failed";
// graceful error handling code here
}
String fullyQualifiedResourceName = "com.package:string/bacon";
int id = resources.getIdentifier(title, null, null);
if (id == 0) {
Log.e(TAG, "Lookup id for resource '"+fullyQualifiedResourceName+"' failed";
// graceful error handling code here
}
ArrayList<Integer> options = new ArrayList<Integer>();
options.add(R.string.bacon);
options.add(R.string.ham);
//R.id.option1 is in my layout and R.string.bacon is in my strings.xml
TextView option1 = (TextView)findViewById(R.id.option1);
option1.setText(options.get(0));