Question

I'm trying to create my own Preference in which I want to give the user the choice to select the new value or to reset to default.

Therefore I need to "store" two values in one preference. I mean, I want to access the stored value and the default value (defined in XML) at the same time.

<my.custom.preference
    myCustomAttribute="R.color.someColor"
    android:defaultValue="@color/someColor"
    android:key="myPref"
/>

In my code, I read the value like this:

String value = attrs.getAttributeValue(null, "myCustomAttribute");

The return value is "R.color.someColor".

So, I tried to get the R-reference of this string, but this is the point where I'm failing.

int neededValue = ???

At the moment, I use a really bad workaround. I search the selected Preference by key and set neededValue programmatically like this:

switch(getKey()) {
case "firstCustomPreference":
     neededColor = R.color.firstColor;
     break;
case "secondCustomPreference":
     neededColor = R.color.secondColor;
     break;
}

This does work, but I really hope there is a cleaner way of doing this.

So my question is: Is there a way to get the int value from the string "R.color.someColor"? Alternatively, is it possible to access the default value?

Was it helpful?

Solution

"Is there a way to get the int value from the String "R.color.someColor"?"

int resourceId = getResources().getIdentifier("someColor", "color", getPackageName());
int color = getResources().getColor(resourceId);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top