2012-02-29 32 views
1

我需要動態訪問xml中的資源。Android - 動態訪問xml資源

res=getResources(); 
plc=res.obtainTypedArray(R.array.id1); 

我願做一個循環=>變化ID1到ID2,ID3,...,ID1000和與各陣列項循環工作。我可以用單個數組來完成,但不能跳轉到另一個數組。任何建議我怎麼能做到這一點? ObtainTypedArray僅將整數作爲參數。

謝謝!

+2

這應該可以幫助你http://stackoverflow.com/q/5406108/839527 – JProgrammer 2012-02-29 00:22:07

+0

謝謝你,JProgrammer。我已閱讀過多次提出的帖子,但無法看到它對我有何用處。我剛剛開始使用java,之前我已經使用了許多其他語言。你能否多加一點你對貧窮小我的智慧? ;-)提前謝謝 – Whitewall 2012-02-29 00:49:55

回答

2

下面是我的從XML調用TypedArray在代碼的問題的精確解:在XML

1)創建數組索引數據數組

<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)調出一個在代碼rray

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=... 

     } 
    } 

感謝您的所有有用的意見,Idecided不使用外地的做法,但我相信,我會到那裏後,我獲得更多的經驗!你可以使這個解決方案更好地使用二維數組,但我沒有用它在我的代碼中...

+0

它有點複雜,難以閱讀,但如果它的工作原理,它的工作原理 – slayton 2012-02-29 15:19:05

1

評論中的答案告訴你如何做到這一點。這裏有一個例子:

讓我們假設你有一個名爲整數: 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); 
} 
+0

謝謝,輝煌!我也發現這個帖子非常有用:http://stackoverflow.com/questions/4326037/android-resource-array-of-arrays ... – Whitewall 2012-02-29 12:23:59