Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

android - Accessing contents of R.string using a variable to represent the resource name

I have a few strings which I need to translate and display. Those strings are in variables. I have the translation in the strings.xml file.

I want to display the "translated version" of the string. For example, inside an Activity:

String name = "Water";
TextView nameDisplay = new TextView(this).
nameDisplay.setText(name);

In the strings file I have the definition

<string name="Water">French word for Water</string>

If I used something like this:

nameDisplay.setText(R.string.KnownName);

it would work. But in my case, the name is stored in a variable so I do not know what to do in order for the setText method to function properly.

My current workaround is

String translation = ""

if(name == "Water") {
  translation = getString(R.string.Water);
}
else {
  ...
}

nameDisplay.setText(translation);

... but this does not scale very well.

Any suggestions?

Should I store the translated version in the variable?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the method to convert string into int identifier:

public static int getStringIdentifier(Context context, String name) {
    return context.getResources().getIdentifier(name, "string", context.getPackageName());
}

Pass in an activity as context parameter (or any other Context instance). Then you can use the identifier as usual with getString() method.

Note that conversion from string to identifier uses reflection and thus can be not that fast, so use carefully.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...