前言
上一章讲了 Fragment 以及系统状态栏、系统底部虚拟按键的换肤,这一章我们来完成自定义 View 的换肤以及字体换肤(字体样式)。
字体样式换肤
如何进行更换字体样式呢?首先,一般我们的字体样式都是放在 assets 目录下的,然后通过 Typeface.createFromAsset();方法返回一个 Typeface,然后 TextView 有一个方法,setTypeface() 就可以设置字体的样式了。
首先我们在换肤框架里面加上下面代码


在 SkinResources 中添加如下代码:
public Typeface getTypeface(int resId){
String skinTypeface = getString(resId);
if(TextUtils.isEmpty(skinTypeface)){
return Typeface.DEFAULT;
}
Typeface typeface;
if(isDefaultSkin){
typeface = Typeface.createFromAsset(mAppResources.getAssets(),skinTypeface);
}else{
typeface = Typeface.createFromAsset(mSkinResources.getAssets(),skinTypeface);
}
return typeface;
}
在 SkinThemeUtil 中添加如下代码
private static int[] TYPEFACE_ATTR = {
R.attr.skinTypeface
};
/**
* 获取更换字体的 Typeface
*/
public static Typeface getSkinTypeface(Activity activity){
int[] resId = getResId(activity, TYPEFACE_ATTR);
return SkinResources.getInstance().getTypeface(resId[0]);
}
然后我们在换肤的时候需要调用一下该方法,并修改其他代码

需要注意一下,字体的换肤一般都是全局性的字体换肤,所以我们在筛选 View 的时候要放宽一下条件



这样就能完成字体样式换肤了
为了能够看清楚字体,我将 MainActivity 布局中某些控件的颜色改了一下。


自定义 View
随便写一个自定义 View,放到 MainActivity 的布局里面。

如图,我放另一个圆在上面,然后颜色设置成了 @color/black,按理说应该和还原按钮的背景颜色一样,换成一样的颜色,但是...

原因很简单,就是因为我们无法知道用户自定义 View 中自定义属性的名字到底是什么,我们无法筛选出需要换肤的自定义 View。
那么我们就提供一个接口,SkinViewSupport
/**
* 解决自定义 View 换肤的问题
*/
public interface SkinViewSupport {
void applySkin();
}
然后,如果你的自定义 View 想换肤,就必须实现我这个接口,并且重写换肤的方法,具体怎么换肤,由使用者自己来写。
然后修改 SkinAttribute 中的代码




最后整理

网友评论