【Android】全局自定义字体的实现

一、修改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对象。

image.png

三、自定义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) {
 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值