I want to access a resource like a String or a Drawable by its name and not its int id.
Which method would I use for this?
Kotlin Version
via Extension Function
To find a resource id by its name In Kotlin, add below snippet in a kotlin file:
ExtensionFunctions.kt
import android.content.Context
import android.content.res.Resources
fun Context.resIdByName(resIdName: String?, resType: String): Int {
resIdName?.let {
return resources.getIdentifier(it, resType, packageName)
}
throw Resources.NotFoundException()
}
Usage
Now all resource ids are accessible wherever you have a context reference using resIdByName
method:
val drawableResId = context.resIdByName("ic_edit_black_24dp", "drawable")
val stringResId = context.resIdByName("title_home", "string")
.
.
.