[英]Android - Access xml resources dynamically
I need to access resources in xml dynamically. 我需要动态访问xml中的资源。
res=getResources();
plc=res.obtainTypedArray(R.array.id1);
I would like to do it in a loop => change id1 to id2, id3, ... ,id1000 and in that loop work with the items of that respective array. 我想在循环=>将id1更改为id2,id3,...,id1000并在该循环中使用该相应数组的项目。 I can do it with single array but can't jump to another one.
我可以使用单个数组但不能跳转到另一个数组。 Any suggestion how I can do that?
有什么建议我怎么做? ObtainTypedArray expects integer only as a parameter.
ObtainTypedArray仅将整数作为参数。
Thank you! 谢谢!
Here is the exact solution to my problem of calling the TypedArray from XML in code: 这是我在代码中从XML调用TypedArray的问题的确切解决方案:
1) in XML create array that indexes data arrays 1)在XML中创建索引数据数组的数组
<array name="arrind">
<item>@array/id1</item>
<item>@array/id2</item>
<item>@array/id3</item>
</array>
<string-array name="id1">
<item>...</item>
<item>....</item>
<item>...</item>
</string-array>
<string-array name="id2">
...
</string-array>
...
2) recall the array in the code 2)在代码中调用数组
Resources res=getResources();
TypedArray index=res.obtainTypedArray(R.array.arrind); //call the index array
for (int i = 0; i < n; i++) {
int id=index.getResourceId(i,0); //get the index
if (id != 0){
String[] handle=new String[n];
handle=res.getStringArray(id); //use the index to get the actual array
String a=handle[0]; //Access items in your XML array
String b=handle[1];
c=...
}
}
Thanks for all your useful advice, Idecided not to use the Field approach but I am sure I will get there after I gain more experience! 感谢您提供所有有用的建议,请注意不要使用Field方法,但我相信在获得更多经验后我会到达那里! You can make this solution even better using 2D array but I have no use for it in my code...
您可以使用2D数组使此解决方案更好,但是我的代码中没有用...
The answer in the comment shows you exactly how to do it. 评论中的答案向您显示了确切的操作方法。 Here is an example:
这是一个例子:
Lets assume you have integers named: id1, id2, id3, id4, ..., id10 you can access them and store them into an array with this: 让我们假设你有一个名为id1,id2,id3,id4,...,id10的整数,你可以访问它们并将它们存储到一个数组中:
int array[] = {1,2,3,4,5,6,7,8,9,10};
int value[10];
for ( i=0; i<10; i++){
String fieldName = "id" + Integer.toString(array[i]);
Field field = R.id.class.getField(fieldName);
value[i] = field.getInt(null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.