'How can I convert the android resources int to a string. eg.: android.R.string.cancel?
How can I obtain the string value "cancel" from this resource int: android.R.string.cancel ?
thank you
Solution 1:[1]
As indicated here: http://developer.android.com/reference/android/content/Context.html#getString(int)
String s = context.getString(android.R.string.cancel);
context can be the current activity, or any object inheriting the Context abstract class.
Solution 2:[2]
This will convert any Android resource into a string. In this example I’ve used an ‘R.color.myColor’ but it will work with any Android resource type.
colors.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="btnDialBgColor">#00BFA5</color>
<color name="btnDialBgColorActive">#C51162</color>
</resources>
TypedValue typedValueActive = new TypedValue();
TypedValue typedValue = new TypedValue();
getResources().getValue(R.color.btnDialBgColorActive, typedValueActive, true);
getResources().getValue(R.color.btnDialBgColor, typedValue, true);
Hope this helps.
Solution 3:[3]
I know that's an old question, but it might help more people. What you can do is to call getIdentifier(). For that, you'll need to call it inserting after what value you want for a this variable, to make the string that you want for your resource ID. For exemple:
Your resources file:
R.string.cancel
In java:
int resourceId = getResources().getIdentifier("cancel", "string", this.getPackageName())
println(getResources().getString(resourceId));
Then, in your rescourceId variable, you'll have an equivalent to: R.string.cancel. And, in println, you'll have the value correspondent of your resources string.
In Kotlin:
val resourceId = this.resources.getIdentifier("cancel", "string", this.packageName)
println(resources.getString(resourceId))
With the same explanation that I said before.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | SirDarius |
| Solution 2 | user2288580 |
| Solution 3 | Raphael Rodrigues |
