自定义字体的TextView

在Android开发中,UI在设计界面时有时会用到一些特殊字体,这就要求我们能自定义一种可改变字体样式的TextView,这里记录一篇自定义的TextView,可实现要求。

首先创建assets文件夹,在里面添加字体文件,如下图:

其次在attrs.xml里面先定义自有的属性:

    <!--自定义字体-->
    <declare-styleable name="TypefaceTextView">
        <attr name="typeface" format="string" />
    </declare-styleable>

然后自定义TextView继续TextView。

package com.******;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatTextView;

import com.****.R;

public class TypefaceTextView extends AppCompatTextView {


    public TypefaceTextView(@NonNull Context context) {
        super(context);
    }

    public TypefaceTextView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initTypefaceTextView(context, attrs);
    }

    public TypefaceTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initTypefaceTextView(context, attrs);
    }

    private void initTypefaceTextView(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TypefaceTextView);
        String type = typedArray.getString(R.styleable.TypefaceTextView_typeface);
        if(null == type){
            return;
        }
        Typeface typeface = null;
        switch (type) {
            case "Alibaba-PuHuiTi-Bold":
                typeface = Typeface.createFromAsset(context.getAssets(), "Alibaba-PuHuiTi-Bold.ttf");
                setTypeface(typeface);
                break;
            case "Alibaba-PuHuiTi-Regular":
                typeface = Typeface.createFromAsset(context.getAssets(), "Alibaba-PuHuiTi-Regular.ttf");
                setTypeface(typeface);
                break;
            default:
                break;
        }
        if (typedArray != null) {
            typedArray.recycle();
        }
        typeface = null;
    }
}

最后使用时,如下即可

    <com.xiding.aistush.widget.TypefaceTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:typeface="Alibaba-PuHuiTi-Bold" 
        android:textSize="20sp"
        android:text="@string/appname"
        android:textColor="@color/white"/>
    
    <!-- Alibaba-PuHuiTi-Bold :assets下字体的名称 -->
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容