Android设置TextView字体

本文介绍如何在Android应用中实现自定义字体的TextView组件。通过创建MultiFontTextView类继承自TextView,并利用FontCustom类来设置不同字体。具体步骤包括放置字体文件到assets目录下、创建自定义视图和设置字体。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.将字体文件(例如HYLiangPinXianCuJ.ttf)放到assets目录下

2.自定义MultiFontTextView继承TextView

public class MultiFontTextView extends TextView {

    public MultiFontTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }
    /**
     * 初始化字体
     * @param context
     */
    private void init(Context context) {
        //设置字体样式
        Typeface typeface = FontCustom.setFont(context);
        if(typeface!=null){
            setTypeface(FontCustom.setFont(context));
        }

    }
}

3.FontCustom类,从sharedPreference中读取之前设置的字体名,并对Typeface类进行设置,如果字体名是默认的,不设置Typeface类

public class FontCustom {


    /**
     * 设置字体
     */
    public static Typeface setFont(Context context) {

        Typeface tf = null;
        String fongUrl = (String) SPUtils.get(context, AppConstants.FONTRESURL, "default");
        Log.i("faongturl", "url:" + fongUrl);


        if ("default".equals(fongUrl)) {

        } else {
            //给它设置你传入的自定义字体文件,再返回回来
            tf = Typeface.createFromAsset(context.getAssets(), fongUrl);
        }

        return tf;
    }


}

4.接下来直接在布局文件中使用即可

  <MultiFontTextView

                android:layout_marginTop="@dimen/app_margin_right"
                android:layout_gravity="center_horizontal"
                android:text="长出一朵花"
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="@dimen/large_text_size"
                android:textColor="@color/black"

                />
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值