我有一个自定义属性,如下所示:
<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并访问属性本身。如果有人可以帮助我更改自定义属性的值,那将是一个很大的帮助。提前谢谢。
发布于 2019-06-12 19:30:27
这很难:)
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;
}
...
}发布于 2019-06-12 19:56:56
在颜色文件中定义特定主题的颜色:
<?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"https://stackoverflow.com/questions/56560657
复制相似问题