[英]Android - Access xml resources dynamically
我需要動態訪問xml中的資源。
res=getResources();
plc=res.obtainTypedArray(R.array.id1);
我想在循環=>將id1更改為id2,id3,...,id1000並在該循環中使用該相應數組的項目。 我可以使用單個數組但不能跳轉到另一個數組。 有什么建議我怎么做? ObtainTypedArray僅將整數作為參數。
謝謝!
這是我在代碼中從XML調用TypedArray的問題的確切解決方案:
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)在代碼中調用數組
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=...
}
}
感謝您提供所有有用的建議,請注意不要使用Field方法,但我相信在獲得更多經驗后我會到達那里! 您可以使用2D數組使此解決方案更好,但是我的代碼中沒有用...
評論中的答案向您顯示了確切的操作方法。 這是一個例子:
讓我們假設你有一個名為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.