user3067903
user3067903

Reputation: 11

Accessing a resource "R.string" variably

In my R.string file I have some questions = R.string.question1, R.string.question2, etc.

When the user clicks a button, with only a number as the text, I want to pull that number(num) and access the string at the correct position (R.string.question[num])

OnClickListener clickQuestion2 = new OnClickListener(){

    @Override
    public void onClick(View arg0) {
        String num = "R.string"+".question"+((Button)arg0).getText().toString();
        int myQuestion = Integer.parseInt(num);
        question.setText(myQuestion);
        int myOption1 = R.string.question2_1;
        int myOption2 = R.string.question2_2;
        int myOption3 = R.string.question2_3;
        int myOption4= R.string.question2_4;
        option1.setText(myOption1);
        option2.setText(myOption2);
        option3.setText(myOption3);
        option4.setText(myOption4); 

Here's the onClickListener for the button. I've tried a couple ways, but nothing seems to work. The error tells me "R.string.question2", for example, is an invalid string. So I know I'm passing it the string for the resource I want, I just don't know how to tell it I want it to read that string, find that resource and parse the int that comes with it. Basically the same as with

int myOption1 = R.string.question2_1;

does. These are the possible answers to the question being pulled from R.string.question(x), and these work. How can I get that int for the resource, but change the resource each time a button is clicked.

If that makes sense, thanks for the help!

EDIT: "question" is a TextView as well as option1, option2, etc.

Upvotes: 0

Views: 174

Answers (2)

Nesim Razon
Nesim Razon

Reputation: 9794

String dynamicString = "question2_1";
int resID = getResources().getIdentifier(dynamicString, "string",  activity.getPackageName()); 
String result = activity.getResources().getString(resID);

Upvotes: 3

Rick Falck
Rick Falck

Reputation: 1778

Use a String array:

<string-array name="question2">
    <item>Sort By Price</item>
    <item>Sort By Magnitude</item>
    <item>Sort By Ingredient Names</item>
    <item>Sort By Extra Effects</item>
</string-array>

Access in code:

int myQuestion = Integer.parseInt(num);
option1.setText(question2[myQuestion]);

Upvotes: 1

Related Questions