简体   繁体   中英

How to get a string from strings.xml by adding int to the name

private int info = 1;

public void nextStep(View view)
{    
    TextView textInfo = (TextView) findViewById(R.id.textInfo);
    textInfo.setText(R.string.info1);
    info++;
}

When one button is clicked, method nextStep is called. And every time a button clicked, I want to show different info, first time it's info1 string, next time it's info2 string and etc. from strings.xml . I would like to do something like that:

private int info = 1;

public void nextStep(View view)
{    
    TextView textInfo = (TextView) findViewById(R.id.textInfo);
    textInfo.setText(R.string.info + info);
    info++;
}

Of course, it's not possible. What should I do? I really don't want to write a big if/else or switch statement. Thanks.

Of course, it's not possible.

Actually, it is. You can use getIdentifier to do this:

private int info = 1;
public void nextStep(View view)
{    
    TextView textInfo = (TextView) findViewById(R.id.textInfo);
    int myStrId = textInfo.getContext().getResources().getIdentifier("info"+info, "string", textInfo.getContext().getPackageName());
    textInfo.setText(myStrId);
    info++;
}

getIdentifer() is a way to fetch resource IDs that are stored in R if you don't know the exact name. While it isn't the most efficient method in the world, it suffices in situations where referencing R (such as your situation) is not possible.

The method returns the same ID that R would; that is, getIdentifier("info1", "id", ...); is the same as R.id.info1 , since R is just a compiled version of it. This method also works in the event that you are unsure if an ID exists (such as from an external library) but need to reference it anyway.

Use an array of String or better a List<String> such as an ArrayList<String> and fill it with the Strings from the XML. Then you can use the get(int index) method to get the ith String in the list.

If you are using JAXB to unmarshall your XML, you can have it set up to create your List for you without much fuss.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM