Reputation: 310
Is it possible to get the String Resource Id specified in strings.xml from the String value ?
<string name="text1">Dummy Text</string>
I know how to get Resource Id (text1) from the String value (Dummy Text), but I want to get Resource Id (text1) from String value(Dummy Text) ? Here is how I get Dummy Text: But I want to get text1(Resource Id) from the Dummy Text value?
context.resources.getIdentifier("text1","string",BuildConfig.APPLICATION_ID)
Upvotes: 1
Views: 1319
Reputation: 6160
I think what you're looking for is the following function that uses reflection:
fun getStringResourceName(stringToSearch: String): String? {
val fields: Array<Field> = R.string::class.java.fields
for (field in fields) {
val id = field.getInt(field)
val str = resources.getString(id)
if (str == stringToSearch) {
return field.name
}
}
return null
}
so by invoking getStringResourceName("Dummy Text")
the function should return "text1".
The function can be even changed a bit to return the resource id corresponding to "Dummy Text":
fun getStringResourceId(stringToSearch: String): Int {
val fields: Array<Field> = R.string::class.java.fields
for (field in fields) {
val id = field.getInt(field)
val str = resources.getString(id)
if (str == stringToSearch) {
return id
}
}
return -1
}
so in this case by calling getStringResourceId("Dummy Text")
you can get something like 2131886277
(the latter number is just an example).
Upvotes: 2