5

Who i can get a random string from the xml string folder?

My xml loks 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 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 input of the TextView is "@string/pr1", but i want the string of the xml who have the name "pr1". Please help. Thanks.

1 Answer 1

2

What you want is to get the id of the resource by name and luckily there is method for this: getIdentifier

So, you should modify your code like this:

botao1.setText(getResources().getIdentifier("rs" + num + ".1", "string", getPackageName());
Sign up to request clarification or add additional context in comments.

4 Comments

What is the "getResources"?, its give me a error Sorry but im new in android and sorry my eglish.
Sorry, typo. It should be getResources().
you should ask a new question.
And why you dont help?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.