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

Viewed 25560

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?

4 Answers

As a Kotlin extension, ArK's answer could be written the following way. It also catches an exception when you give it an unknown key.

fun Context.getStringWithResKey(nameResKey: String): String {
    val resId = resources.getIdentifier(nameResKey, "string", packageName)
    return try {
        getString(resId)
    } catch (e: Exception) {
        Log.e(this.javaClass.simpleName, "Couldn't find string value for key '$nameResKey'", e)
        ""
    }
}
Related