一、修改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) {
view.typeface = typeface

本文介绍了如何在Android应用中全局自定义字体,通过修改Factory2并自定义实现,达到修改所有TextView字体的效果。同时,文章提到了Jetpack Compose作为新的UI框架,其优势在于简化开发、提升速度,并提供了学习资源。
最低0.47元/天 解锁文章
1019

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



