我目前面临一个问题,是否可以使用这样的功能“findViewById()
”?findViewById函数使用字符串变量
String[] names{ "a", "b"};
findViewById(R.drawable.names[0]);
我目前面临一个问题,是否可以使用这样的功能“findViewById()
”?findViewById函数使用字符串变量
String[] names{ "a", "b"};
findViewById(R.drawable.names[0]);
编辑:只要你知道,你只能叫findViewById
上R.id
类型。因此,您的代码必然会失败,因为您在R.drawable
类型中调用它。
尝试getIdentifier()
。 Documentation
int resourceId = getResources().getIdentifier(names[0], "drawable", getPackageName());
findViewById(resourceId);
注:Android的文件说:
使用此功能被劝阻。 通过标识符而不是按名称检索资源要高效得多。
在这种情况下,它很可能会更好,如果你定义的int
数组,那些包含在drawable
资源的ID。
没有你不能这样做,而是有相应的解决方法。尝试是这样的: -
String[] names{ "a", "b"};
int drawableId = this.getResources().getIdentifier(names[0], "drawable", this.getPackageName());
findViewById(drawableId);
凡this
是一种活动,写只是为了澄清。
如果你想有一个String
在的strings.xml或UI元素的identifier
,替代“绘制”
int resourceId = this.getResources().getIdentifier("nameOfResource", "id", this.getPackageName());
我必须警告你,获得标识的这种方式实在是太慢了,只在需要的地方使用。
我不认为你的答案是错误的或不相关的。所以我会中立downvote。 – 2013-03-19 07:19:56
findViewById()accept int not string。所以,你可以像使用..
int[] txtViewIdsform1;
txtViewIdsform1 = new int[] { R.drawable.txt_phone1, R.drawable.txt_phone2,
R.drawable.txt_fax, R.drawable.txt_contact_name, R.drawable.txt_contact_ph};
没有这个不能做
你可以做其他的方式就像
int[] ids={R.drawable.a,R.drawable.b};
findViewById(ids[0]);
没有,findViewById()接受INT(查看ID)为参数。 – SKK 2013-03-19 07:13:36
'findViewById'和'R.drawable'?似乎合法.. – 2013-03-19 07:20:10