介绍一个开源工程
https://github.com/dersoncheng/MultipleTheme
扩展使用:
第一步:在项目的attr.xml声明自定义属性(各种模式都会用到的属性)
第二步:在项目的style.xml指定各种模式主题下的自定义属性值
第三步:在页面布局文件里使用自定义属性值
第四步:在基类的onCreate方法里添加切换主题模式的逻辑代码
第五步:调用工具类方法切换主题模式
第六步:针对切换主题模式时需要立即更新页面ui的页面,需要使用框架里的封装控件
控件放置,并引用一个属性
<derson.com.multipletheme.colorUi.widget.ColorButton
android:id="@+id/btn"
android:text="换肤"
android:layout_centerInParent="true"
android:textColor="?attr/main_textcolor"
android:layout_width="100dip"
android:layout_height="80dip" />
定义自定义控件时,有
this.attr_background = ViewAttributeUtil.getBackgroundAttibute(attrs);
然后
@Override
public void setTheme(Resources.Theme themeId) {
ViewAttributeUtil.applyBackgroundDrawable(this, themeId, attr_background);
ViewAttributeUtil.applyTextAppearance(this, themeId, attr_textAppreance);
}
迭代调用,使得控件树都重新setTheme
/**
* 切换应用主题
*
* @param rootView
*/
public static void changeTheme(View rootView, Resources.Theme theme) {
if (rootView instanceof ColorUiInterface) {
((ColorUiInterface) rootView).setTheme(theme);
if (rootView instanceof ViewGroup) {
int count = ((ViewGroup) rootView).getChildCount();
for (int i = 0; i < count; i++) {
changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
}
}
if (rootView instanceof AbsListView) {
try {
Field localField = AbsListView.class.getDeclaredField("mRecycler");
localField.setAccessible(true);
Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear", new Class[0]);
localMethod.setAccessible(true);
localMethod.invoke(localField.get(rootView), new Object[0]);
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
} catch (NoSuchMethodException e3) {
e3.printStackTrace();
} catch (IllegalAccessException e4) {
e4.printStackTrace();
} catch (InvocationTargetException e5) {
e5.printStackTrace();
}
}
} else {
if (rootView instanceof ViewGroup) {
int count = ((ViewGroup) rootView).getChildCount();
for (int i = 0; i < count; i++) {
changeTheme(((ViewGroup) rootView).getChildAt(i), theme);
}
}
if (rootView instanceof AbsListView) {
try {
Field localField = AbsListView.class.getDeclaredField("mRecycler");
localField.setAccessible(true);
Method localMethod = Class.forName("android.widget.AbsListView$RecycleBin").getDeclaredMethod("clear", new Class[0]);
localMethod.setAccessible(true);
localMethod.invoke(localField.get(rootView), new Object[0]);
} catch (NoSuchFieldException e1) {
e1.printStackTrace();
} catch (ClassNotFoundException e2) {
e2.printStackTrace();
} catch (NoSuchMethodException e3) {
e3.printStackTrace();
} catch (IllegalAccessException e4) {
e4.printStackTrace();
} catch (InvocationTargetException e5) {
e5.printStackTrace();
}
}
}
}
final View rootView = getWindow().getDecorView();
ColorUiUtil.changeTheme(rootView, getTheme());