Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android | Kotlin | How to get a text using a variable ID within getString()

Tags:

android

kotlin

I tried a lot of combinations, but somehow I don't get it.

The id for the text I want to show is generated.

I need to write a variable here instead of a concrete id.

So not:

getString(R.string.id_1)

But something like:

var myId = ... 
getString(R.string."$myId")

Do you know what I mean? What ever I tried I got an error that only an Int.

How would you solve this in Kotlin?

like image 327
user21681 Avatar asked Oct 16 '22 21:10

user21681


1 Answers

Try below code, it will work for you:

fun AppCompatActivity.getString(name: String): String {
   return resources.getString(resources.getIdentifier(name, "string", packageName))
}

Usage: val resource = getString($resourceName);
like image 179
Dhaval Patel Avatar answered Oct 24 '22 05:10

Dhaval Patel