Android gets random string on xml string
Who can I get a random string from an xml string folder?
My xml locks like:
<string name="pr1">Question 1</string>
<string name="rs1.1">Aswer 1</string>
<string name="rs1.2">Aswer 2</string>
<string name="rs1.3">Aswer 3</string>
<string name="rs1.4">Aswer 4</string>
<string name="pr2">Question 2</string>
<string name="rs2.1">Aswer 1</string>
<string name="rs2.2">Aswer 2</string>
<string name="rs2.3">Aswer 3</string>
<string name="rs2.4">Aswer 4</string>
And I want to do something like this:
Random r = new Random();
int num=r.nextInt(2);
TextView aswer= (TextView) findViewById(R.id.textView);
Button botao1 = (Button) findViewById(R.id.button3);
botao1.setText("@string/rs"+num+".1");
aswer.setText("@string/pr"+num);
But the TextView input is "@ string / pr1", but I need an xml string that has the name "pr1". Please help. Thank.
What you want is to get the resource identifier by name and, fortunately, there is a way for this: getIdentifier
So you should change your code as follows:
botao1.setText(getResources().getIdentifier("rs" + num + ".1", "string", getPackageName());