简体   繁体   English

从自定义首选项访问默认值

[英]Access default value from custom preference

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. 我正在尝试创建自己的Preference在其中我希望为用户提供选择新值或重置为默认值的选择。

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. 我的意思是,我想同时访问存储的值和默认值(以XML定义)。

<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" . 返回值为"R.color.someColor"

So, I tried to get the R-reference of this string, but this is the point where I'm failing. 因此,我尝试获取此字符串的R引用,但这是我失败的地方。

int neededValue = ???

At the moment, I use a really bad workaround. 目前,我使用了非常糟糕的解决方法。 I search the selected Preference by key and set neededValue programmatically like this: 我通过关键字搜索所选的Preference ,并neededValue编程方式设置neededValue如下所示:

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" ? 所以我的问题是:有没有办法从字符串"R.color.someColor"获取int值? Alternatively, is it possible to access the default value? 或者,可以访问默认值吗?

"Is there a way to get the int value from the String "R.color.someColor"?" “有没有办法从字符串“ R.color.someColor”中获取int值?”

int resourceId = getResources().getIdentifier("someColor", "color", getPackageName());
int color = getResources().getColor(resourceId);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM