1

Pretty much I've been trying to figure this out for the past hour.
I want to generically get strings from strings.xml and in to my code so I can dynamically change the amount of strings without having to change anything in my code that loads them in to the array list.

So far all I have is

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 */);

I can not figure out for the life of me how to get the string value out of the field object. All I am getting is either Id's [or at least what I think is an Id] or the name I've assigned it inside the strings.xml file.

4

3 回答 3

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));
            }
于 2012-11-06T05:47:38.900 回答
1

Create an XML file example.xml in res/xml folder

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

then parse it as shown below

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();
}
于 2012-11-06T05:57:12.680 回答
0

You can try this :

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

string1 is a string constant in strings.xml

于 2012-11-06T05:57:43.513 回答