Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 899
MyName Avatar asked Aug 21 '10 19:08

MyName


People also ask

Why should you use string resources instead of hard coded strings in your apps?

It is not good practice to hard code strings into your layout files. You should add them to a string resource file and then reference them from your layout. This allows you to update every occurrence of the word "Yellow" in all layouts at the same time by just editing your strings.

What is the use of string xml?

A string resource provides text strings for your application with optional text styling and formatting. There are three types of resources that can provide your application with strings: String. XML resource that provides a single string.

In which folder can you find the string resource file strings xml?

You can find strings. xml file inside res folder under values as shown below.

How do you do plurals in Android?

Multiple quantities in one string If your display text has multiple quantities, e. g. %d match(es) found in %d file(s). , split it into three separate resources: %d match(es) ( plurals item) %d file(s) ( plurals item)


1 Answers

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.

like image 72
Konstantin Burov Avatar answered Oct 14 '22 03:10

Konstantin Burov