2012-11-06 196 views
1

在過去的一個小時裏,我一直試圖弄清楚這一點。
我想一般從strings.xml得到字符串,並在我的代碼,所以我可以動態更改字符串的數量,而無需更改我的代碼中的任何東西,將它們加載到數組列表中。

到目前爲止,我只有如何從strings.xml中獲取字符串值並進入arraylist [android]

for(Field x :R.string.class.getFields()) 
     if(x.getName().startsWith("ans")) 
      choices.add(/*what do I add here to get the string value from the field in to the arraylist */); 

我想不出我的生活如何得到字符串值了現場的對象。我得到的所有內容都是Id(或者至少我認爲是Id)或我在strings.xml文件中分配的名稱。

回答

4
Resources res = getResources(); 
    for(Field x :R.string.class.getFields()) 
     if(x.getName().startsWith("ans")){ 
       int id = x.get(null); 
       choices.add(res.getString(id)); 
      } 
+0

是的,只是不得不改變x.get(null)並將其作爲一個整數和環繞一個嘗試,趕上 但這是我渴望的正確解決方案。 –

+0

有人請這個。 –

+0

try {choices.add(res.getString((Integer)x.get(null))); } //這獲取ID,然後抓住相關 \t \t \t \t \t \t \t \t趕上(拋出:IllegalArgumentException E){e.printStackTrace()的資源;} \t \t \t \t趕上(IllegalAccessException E){e.printStackTrace ();} \t} –

1

創建RES/XML文件夾中的XML文件的example.xml

<?xml version="1.0" encoding="utf-8"?> 
<data> 
    <record name="foo" /> 
</data> 

然後分析它如下圖所示

XmlResourceParser xrp = context.getResources().getXml(R.xml.example); 
try { 
    int eventType = xrp.next(); 
    while (eventType != XmlPullParser.END_DOCUMENT) { 
    if (eventType == XmlPullParser.START_TAG && xrp.getName().equalsIgnoreCase("record")) { 

     String name = xrp.getAttributeValue(null, "name"); 

     //choices.add(name); 
    } 

    eventType = xrp.next(); 
    } 
} catch (XmlPullParserException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
+0

這太費力了。我想用反射。 Faylons的回答是我的需求的正確解決方案。 –

0

你可以試試這個:

choices.add(getResources().getString(R.string.string1)); 

string1是strings.xml中的字符串常量

+0

不夠通用。我想從一個循環中添加,而不是從一堆添加硬編碼的add()語句中添加,這會導致維護問題。 –

相關問題