MrMinemeet MrMinemeet - 3 months ago 27
Android Question

Choose a random text from string.xml

I have a string.xml file full of text_1 ... text_100
Now I want to choose a random text of these and display it on a TextView.
I tried to use

String text = "text_";
int randomNum = rand.nextInt((100 + 1) + 1;
text = text + String.valueOf(randomNum);
txt.setText(getString(R.string.text);


so now it doesn't work because there is no "text" in the string file...

maybe some suggestions?

Answer Source

You can use this, but it is bad practise:

public static int getResId(String resName, Class<?> c) {
    try {
        Field idField = c.getDeclaredField(resName);
        return idField.getInt(idField);
    } catch (Exception e) {
        e.printStackTrace();
        return -1;
    } 
}

In your case:

getResId(text, String.class);

Better option is to create array of strings in xml:

<?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>

and then:

String[] planets = res.getStringArray(R.array.planets_array);
int randomNum = rand.nextInt(planets.size() - 1);
txt.setText(planets[randomNum]);