1

I have the strings.xml file looking like this:

<resources>
    <string name="key1">value1</string>
    <string name="key2">value2</string>
</resources>

In the code I have got the string "key1".
Now I want to access the value "value1" in my strings.xml file.
How can I get the value having the key only as string? Is there a way to to this?
The only way I see is to instantiate some map mapping the key as string to the resouce IDs.

val map = mapOf("key1" to R.string.key1, "key2" to R.string.key2)
val value1 = map["key1"]

But maybe there is a simpler solution...

Thank you for your help!

Laufwunder
  • 773
  • 10
  • 21
  • 4
    Does this answer your question? [Android, getting resource ID from string?](https://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string) – ashu Oct 31 '20 at 12:10

1 Answers1

-1

If you are inside an Activity Class, this will do:

String value1 = getString(R.string.key1);

If you want to get String value from any class, do this:

String value2 = Resources.getSystem().getString(R.string.key2);

Hope this helps. If you have any question about this, please feel free to ask.

Rohit Rawat
  • 449
  • 1
  • 4
  • 14
  • 1
    This is not what OP asked. OP wants to get string resources using string identifiers as opposed to the regular integer identifiers. – ashu Oct 31 '20 at 15:07
  • But if you are familiar with Android Resources, you should know that "key" string identifiers are stored as Integer Resource ID in Resource files, and one can access them in this way - R.[res_type].[identifier_name] – Rohit Rawat Nov 01 '20 at 08:44
  • Like I commented on the question, it is possible to get integer references using strings. https://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string – ashu Nov 01 '20 at 10:13