2013-03-19 114 views
2

我目前面临一个问题,是否可以使用这样的功能“findViewById()”?findViewById函数使用字符串变量

String[] names{ "a", "b"}; 
findViewById(R.drawable.names[0]); 
+0

没有,findViewById()接受INT(查看ID)为参数。 – SKK 2013-03-19 07:13:36

+2

'findViewById'和'R.drawable'?似乎合法.. – 2013-03-19 07:20:10

回答

2

编辑:只要你知道,你只能叫findViewByIdR.id类型。因此,您的代码必然会失败,因为您在R.drawable类型中调用它。

尝试getIdentifier()Documentation

int resourceId = getResources().getIdentifier(names[0], "drawable", getPackageName()); 
findViewById(resourceId); 

注:Android的文件说:

使用此功能被劝阻。 通过标识符而不是按名称检索资源要高效得多。

在这种情况下,它很可能会更好,如果你定义的int数组,那些包含在drawable资源的ID。

1

没有你不能这样做,而是有相应的解决方法。尝试是这样的: -

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()); 

我必须警告你,获得标识的这种方式实在是太慢了,只在需要的地方使用。

+0

我不认为你的答案是错误的或不相关的。所以我会中立downvote。 – 2013-03-19 07:19:56

0

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}; 
0

没有这个不能做

你可以做其他的方式就像

int[] ids={R.drawable.a,R.drawable.b}; 
findViewById(ids[0]);