2017-05-04 62 views
1

所以我有很多的strings.xml字符串,它們被記錄在一個格式:的Android的getString問題

<string name="list_1">xxxxxxxxxxx</string> 
<string name="list_2">xxxxxxxxxxx</string> 
<string name="list_3">xxxxxxxxxxx</string> 
...... 

現在我想通過一個加載它們一個,而不必鍵入所有字符串ID。我想以類似的方式加載它們:

for (int i = 1; i <= num; i++) { 

    // Just showing what I mean. 
    String xxx = getString(R.string.("list_" + i)); 

} 

是否有一種方法可以這樣做?

+0

[試試這個(http://stackoverflow.com/a/11595723/1790644)。 –

回答

1

試試這個:

int resourceID = getResources().getIdentifier("list_" + i, "string", getPackageName()); 

String xxx = getString(resourceID); 
+0

非常感謝。非常感謝! –

1

這將是值得使用的資源數組。例如

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <string-array name="planets_array"> 
     <item>Mercury</item> 
     <item>Venus</item> 
     <item>Earth</item> 
     <item>Mars</item> 
    </string-array> 
</resources> 

,您可以訪問,迭代如下:

Resources res = getResources(); 
String[] planets = res.getStringArray(R.array.planets_array);