2

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?

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
chris115379
  • 312
  • 3
  • 13

1 Answers1

1

"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);
Peter
  • 540
  • 3
  • 12
  • 1
    Thanks. You helped me a lot. Some further Information are [here](http://stackoverflow.com/questions/4427608/android-getting-resource-id-from-string) – chris115379 May 01 '14 at 13:49