Android 使用字符串变量的findViewById函数

Android 使用字符串变量的findViewById函数,android,Android,我目前面临一个问题,是否可以像这样使用函数“findViewById()” String[] names{ "a", "b"}; findViewById(R.drawable.names[0]); 编辑:正如您所知,您只能在R.id类型上调用findViewById。因此,由于您在R.drawable类型上调用代码,因此您的代码注定会失败 尝试getIdentifier() 注意:Android文档中说: 不鼓励使用此功能。这样做效率更高 按标识符而不是按名称检索资源 在这种情况下,如果您定

我目前面临一个问题,是否可以像这样使用函数“
findViewById()

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

编辑:正如您所知,您只能在
R.id
类型上调用
findViewById
。因此,由于您在
R.drawable
类型上调用代码,因此您的代码注定会失败

尝试
getIdentifier()

注意:Android文档中说:

不鼓励使用此功能。这样做效率更高 按标识符而不是按名称检索资源


在这种情况下,如果您定义一个
int
数组,以及那些包含
可绘制资源的id的数组,可能会更好。

EDIT:您知道,您只能在
R.id
类型上调用
findViewById
。因此,由于您在
R.drawable
类型上调用代码,因此您的代码注定会失败

尝试
getIdentifier()

注意:Android文档中说:

不鼓励使用此功能。这样做效率更高 按标识符而不是按名称检索资源


在这种情况下,如果您定义了一个
int
数组,以及那些包含
可绘制的
资源ID的数组,可能会更好。

您不能这样做,但是有一个解决方法。试着这样做:-

String[] names{ "a", "b"};
int drawableId = this.getResources().getIdentifier(names[0], "drawable", this.getPackageName());
findViewById(drawableId);
其中,
是一项活动,仅为澄清而编写

如果希望在strings.xml中使用
String
或UI元素的
identifier
,请替换为“drawable”


我必须警告您,这种获取标识符的方法非常慢,只能在需要的地方使用。

您不能这样做,但是有一种解决方法。试着这样做:-

String[] names{ "a", "b"};
int drawableId = this.getResources().getIdentifier(names[0], "drawable", this.getPackageName());
findViewById(drawableId);
其中,
是一项活动,仅为澄清而编写

如果希望在strings.xml中使用
String
或UI元素的
identifier
,请替换为“drawable”

我必须警告您,这种获取标识符的方法非常慢,只在需要时使用。

findviewbyd()接受int而不是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};
findViewById()接受int而不是字符串。所以你可以用像

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]);
不,这不可能

你可以用另一种方式做

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

否,findViewById()接受int(视图id)作为参数。
findViewById
R.drawable
?似乎合法..不,findViewById()接受int(视图id)作为参数。
findViewById
R.drawable
?似乎是合法的。我不认为你的答案是错的或不相关的。所以,我将中和反对票。我不认为你的答案是错误的或无关紧要的。所以我要中和反对票。