本文介绍了设置自定义属性android的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的自定义属性:
I have a custom attribute say like this :
<attr name="colorPrimarySdk" format="color"/>
<attr name="colorSecondarySdk" format="color"/>
<attr name="colorAccentSdk" format="color"/>
我正在以这种样式使用它们:
And I am using them in my styles like this:
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">?colorPrimarySdk</item>
<item name="colorPrimaryDark">?colorSecondarySdk</item>
<item name="colorAccent">?colorAccentSdk</item>
</style>
现在我想要的是从代码中动态设置属性值,例如:
Now what I want is to set the value of my attributes dynamically from the code like, say :
colorPrimarySdk.value = myCustomColor
我已经尝试使用TypedValue并访问属性本身.如果有人可以帮助更改我的自定义属性的值,那将是一个很大的帮助.提前致谢.
I have already tried using TypedValue and accessing the attribute itself.If anyone can help changing the value for my custom attribute, that would be a great help. Thanks in advance.
推荐答案
很难:)
colors.xml:
colors.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="your_special_color">#FF0099CC</color>
</resources>
Res.java:
public class Res extends Resources {
public Res(Resources original) {
super(original.getAssets(), original.getDisplayMetrics(), original.getConfiguration());
}
@Override public int getColor(int id) throws NotFoundException {
return getColor(id, null);
}
@Override public int getColor(int id, Theme theme) throws NotFoundException {
switch (getResourceEntryName(id)) {
case "your_special_color":
// You can change the return value to an instance field that loads from SharedPreferences.
return Color.RED; // used as an example. Change as needed.
default:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return super.getColor(id, theme);
}
return super.getColor(id);
}
}
}
BaseActivity.java
BaseActivity.java
public class BaseActivity extends AppCompatActivity {
...
private Res res;
@Override public Resources getResources() {
if (res == null) {
res = new Res(super.getResources());
}
return res;
}
...
}
这篇关于设置自定义属性android的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!