Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: dynamic key-names R.string

Tags:

android

i have a strings.xml file:

<string name="wind_direction_n">North</string>
<string name="wind_direction_nne">North-Northeast</string>
<string name="wind_direction_ne">Northeast</string>
<string name="wind_direction_ene">East-Northeast</string>
<string name="wind_direction_e">East</string>
<string name="wind_direction_ese">East-Southeast</string>
<string name="wind_direction_se">Southeast</string>
<string name="wind_direction_sse">South-Souteast</string>
<string name="wind_direction_s">South</string>
<string name="wind_direction_ssw">South-Southwest</string>
<string name="wind_direction_sw">Southwest</string>
<string name="wind_direction_wsw">West-Southwest</string>
<string name="wind_direction_w">West</string>
<string name="wind_direction_wnw">West-Norhwest</string>
<string name="wind_direction_nw">Northwest</string>
<string name="wind_direction_nnw">North-Northwest</string>

And i need something like this:

String direction = "nn";
String message = R.string["wind_direction" + direction]

How can i do this?

Freddy

like image 931
Freddy Ochner Avatar asked Aug 31 '25 16:08

Freddy Ochner


1 Answers

You can do it accessing to runtime generated resources by name:

String direction = "nn";
String fullName = "wind_direction" + direction;

// Get the identifier of the resource by its name.
@StringRes int resId = getResources().getIdentifier(fullName, "string", getPackageName());
// Use the value of the resource.
String message = getString(resId);
like image 140
Giorgio Antonioli Avatar answered Sep 02 '25 19:09

Giorgio Antonioli