修改android app 字体格式


首先将项目需要的字体资源放置在app下:
放置需要的字体文件

这是我自己找的字体文件,分别代表粗体,方正准圆,华文彩云,华文行楷,华文新宋,华文新魏,幼圆。
注意,字体ttf文件只能用英文字母,中文会报找不到文件异常。

我们先看看未设置之前的布局样式:
原始图片
字体文件准备好后,我们就可以按需设置自己想要的字体样式。下面提供了3种设置方法,这3种方法都可以改变可以显示文本的控件字体样式,如TextView,Button,EditText,CheckBox,RadioButton等等:

方法1:自定义控件 FontTextView

重写TextView,重写其中的setTypeface方法,设置自己的字体样式

package com.laundrylang.laundrylangpda.view;
public class FontTextView extends TextView{
     

    public FontTextView(Context context) {
        super(context);
    }

    public FontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FontTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private Typeface createTypeface(Context context, String fontPath) {
        return Typeface.createFromAsset(context.getAssets(), fontPath);
    }


    @Override
    public void setTypeface(Typeface tf, int style) {
        super.setTypeface(createTypeface(getContext(),"fonts/fzzy.ttf"), style);
    }
}

布局中直接用自定义的FontTextView类即可。

<com.laundrylang.laundrylangpda.view.FontTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个TextView"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个Button"/>
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个EditText"/>
    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个CheckBox"/>
    <RadioButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是一个RadioButton"/>

前后对照布局文件,因为这里只重写了TextView,所以只有TextView有变化:
第一种方式设置

这种设置方式的优缺点:
优点:使用简单方便,不需要额外的工作。
缺点:只能替换一类控件的字体,如果需要替换Button或EditText控件的字体,需要以相同的方式自定义这些控件,这样工作量大。

方法2:递归批量替换某个View及其子View的字体

Android中可显示文本的控件都直接或间接继承自TextView,批量替换字体的原理就是从指定的View节点开始递归遍历所有子View,如果子View类型是TextView类型或其子类型则替换字体,如果子View是ViewGroup类型则重复这一过程。我抽取了一个工具类,代码如下:

public class TypefaceUtil {
     

    /**
     * <p>Replace the font of specified view and it's children</p>
     * @param root The root view.
     * @param fontPath font file path relative to 'assets' directory.
     */
    public static void replaceFont(@NonNull View root, String fontPath) {
        if (root == null || TextUtils.isEmpty(fontPath)) {
            return;
        }


        
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值