0

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?

Natig Babayev
  • 3,128
  • 15
  • 23
M Deckers
  • 3
  • 1
  • From the link, I'm guessing this is a question about the Android API; if so, adding a suitable tag to the question, and/or mentioning that explicitly, might help provide some context.  Also, it might help to explain what this code is intended to do. – gidds Dec 31 '19 at 14:06
  • R is not a repository of data. It is just a list of pointers. It is used for finding objects and does not contain any data from those objects. In your example above, leave off the $. It should already be a property if it is that file. R.String.category__service would access that one. If you want selectables you need to create xml arrays inside the strings file and access them properly as arrays. – John Lord Dec 31 '19 at 19:22
  • @JohnLord leaving off the $ would not work since I have multiple categories and I wanted to walk trough them and I didn't want to hardcode R.string.category__service, R.string.category__other etc. I have looked at xml arrays in the documentation and it seems you can't acces them by key - meaning their key is numeric. But I'd need something like category['service'] – M Deckers Jan 01 '20 at 13:45

1 Answers1

1

You can try following:

val key = "category__$this.name" // "category__service"
val s = resources.getIdentifier(key, "string", context.packageName)
Natig Babayev
  • 3,128
  • 15
  • 23