我有一个这样的自定义属性:
<attr name="colorPrimarySdk" format="color"/>
<attr name="colorSecondarySdk" format="color"/>
<attr name="colorAccentSdk" format="color"/>
我正在以这种样式使用它们:
<style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">?colorPrimarySdk</item>
<item name="colorPrimaryDark">?colorSecondarySdk</item>
<item name="colorAccent">?colorAccentSdk</item>
</style>
现在我想要的是从代码中动态设置属性值,例如:
colorPrimarySdk.value = myCustomColor
我已经尝试使用TypedValue并访问属性本身。 如果有人可以帮助更改我的自定义属性的值,那将是一个很大的帮助。提前致谢。
答案 0 :(得分:0)
很难:)
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
public class BaseActivity extends AppCompatActivity {
...
private Res res;
@Override public Resources getResources() {
if (res == null) {
res = new Res(super.getResources());
}
return res;
}
...
}
答案 1 :(得分:0)
在您的颜色文件中为特定主题定义颜色:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="my_link_color1">#0077CC</color>
<color name="my_link_color2">#626262</color>
</resources>
创建包含以下内容的文件res / values / attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="myLinkColor" format="reference" />
</resources>
假设在styles.xml中有两个主题(Theme1和Theme2)定义:
<style name="Theme1" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="myLinkColor">@color/my_link_color1</item>
</style>
<style name="Theme2" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="myLinkColor">@color/my_link_color2</item>
</style>
使用XML中的颜色:
android:textColor="?attr/myLinkColor"