M Deckers
M Deckers

Reputation: 3

Use string variable as object key

I have strings in my strings.xml e.g.:

<string name="category__service">Service</string>

I want to access them like this:

val key = "category__$this.name" // "category__service"
val s = R.string.[key]

This would give me the Id of the string which I can use. But this way I get the error

The expression cannot be a selector (occur after a doted text)

I also tried

val s = R.string.$key

but I get:

Expecting an element

The documentation on what R is to begin with, isn't giving me much. As far as I see – R.string does not have a simple getter.

So at this point I'm just guessing for a solution. Is this even possible in Kotlin?

Upvotes: 0

Views: 960

Answers (1)

Natig Babayev
Natig Babayev

Reputation: 3296

You can try following:

val key = "category__$this.name" // "category__service"
val s = resources.getIdentifier(key, "string", context.packageName)

Upvotes: 1

Related Questions