一、修改TextView字体
假设现在有一个字体文件msyh.ttf
;对于某个TextView来说,如果想修改它的字体,可以简单的使用如下代码:
val tv = findView()
val tf = Typeface.createFromAsset(assets, "msyh.ttf")
tv.typeface = tf
这样就可以将单个TextView设置为对应字体。如果想要实现全局修改字体,则需要通过修改Factory2的方式来实现。
二、Factory2
Factory2用于根据xml标签创建实例对象的过程。
众所周知,在初始化布局的时候,会调用LayoutInflater.inflate
方法,而其会尝试使用LayoutInflater.tryCreateView
方法来创建View对象。该方法如下:
public final View tryCreateView(@Nullable View parent, @NonNull String name,
@NonNull Context context, @NonNull AttributeSet attrs) {
// ……
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
// ……
return view;
}
可以看到,其会优先调用mFactory2.onCreateView
来创建对象。所以,如果可以替换LayoutInflater.mFactory2
这个对象,就可以操纵布局的创建过程。
那么,mFactory2
对象又是从何而来的呢?通过打断点Debug,可以追踪到,系统默认的Factory2是在onCreate
方法中设置的,而其也就是AppCompatActivity.mDelegate
对象。
三、自定义Factory2
由于已经知道系统默认的Factory2就是AppCompatActivity.mDelegate
,则可自定义Factory2如下:
val myFactory2 = object : LayoutInflater.Factory2 {
override fun onCreateView(parent: View?, name: String, context: Context, attrs: AttributeSet): View? {
val delegate = activity.delegate
val view = delegate.createView(parent, name, context, attrs)
if (view is TextView) {