最近遇到改变app主题颜色的需求,其实很简单,就是设置好主题,然后把所有设置颜色的地方改成attr获取。直接看具体实现。
color.xml文件:颜色该怎么设置怎么设置就行了
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="black">#FF000000</color>
<color name="white">#FFFFFFFF</color>
<color name="color_FFFF0000">#FFFF0000</color>
<color name="color_FF00FF00">#FF00FF00</color>
</resources>
attrs.xml文件:定义颜色名称
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- 主题颜色,外层这个declare-styleable可以去掉,测试发现包不包这层效果一样 -->
<declare-styleable name="MyColor">
<attr name="colorPrimary" format="reference|color" />
<attr name="colorBackground" format="reference|color" />
</declare-styleable>
</resources>
themes.xml文件:定义主题,这里每个主题都设置了attrs文件中的颜色对应值
<resources>
<!-- 深色主题 -->
<style name="AppTheme.MyDark" parent="Theme.AppCompat.DayNight">
<item name="colorPrimary">@color/black</item>
<item name="colorBackground">@color/white</item>
</style>
<!-- 浅色主题 -->
<style name="AppTheme.MyLight" parent="Theme.AppCompat.DayNight">
<item name="colorPrimary">@color/color_FFFF0000</item>
<item name="colorBackground">@color/color_FF00FF00</item>
</style>
</resources>
AndroidManifest.xml文件中application设置默认主题
android:theme="@style/AppTheme.MyDark"
xml文件中设置颜色,方式就是 ?attr/xxx ,其中xxx是在attrs文件中定义的
android:background="?attr/colorBackground"
android:textColor="?attr/colorTextPrimary"
代码中设置颜色,下面两种方式都行
public class ResourceUtil {
@ColorInt
public static int getColor(Context context, @AttrRes int attrId){
int[] attribute = new int[] { attrId };
TypedArray array = context.getTheme().obtainStyledAttributes(attribute);
int color = array.getColor(0, Color.TRANSPARENT);
array.recycle();
return color;
}
@ColorInt
public static int getColor2(Context context, @AttrRes int attrId){
TypedValue typedValue = new TypedValue();
if (context.getTheme().resolveAttribute(attrId,typedValue,true))
return typedValue.data;
else
return Color.TRANSPARENT;
}
}
activity中设置和更改主题,使用SharedPreferences保存当前主题,通过setTheme(int theme)方法设置主题,修改sp之后调用recreate()重启资源
protected Boolean myTheme;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//这个主题设置要在super.onCreate之前做,否则不生效的
SharedPreferences sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);//获取主题更换状态
myTheme = sharedPreferences.getBoolean("isLightTheme", true);//第一次默认设置为亮色主题
if (!myTheme) {
setTheme(R.style.AppTheme_MyDark);//黑色主题
} else {
setTheme(R.style.AppTheme_MyLight);//亮色主题
}
super.onCreate(savedInstanceState);
}
//点击事件修改主题
@Override
public void onClick(View v) {
if (v.equals(binding.ivTheme)){
myTheme= !myTheme;//切换主题状态
recreate();//重启资源
SharedPreferences sharedPreferences = getSharedPreferences("config", MODE_PRIVATE);//获取主题更换状态
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("isLightTheme", myTheme);//存储主题更换状态
editor.commit();
}
}
就是这些了!!
本文介绍了如何在Android应用中实现主题颜色的切换。主要涉及color.xml、attrs.xml、themes.xml文件的配置,以及在AndroidManifest.xml中设置默认主题。在布局xml中使用?attr/xxx引用自定义颜色,代码中可以通过SharedPreferences保存和切换主题,使用setTheme(int theme)并调用recreate()方法更新资源。
1708

被折叠的 条评论
为什么被折叠?



