Reputation: 21759
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.
Upvotes: 2
Views: 221
Reputation: 67522
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.
Upvotes: 3
Reputation: 285450
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.
Upvotes: 1