且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在.xml文件而不是.java文件中设置自定义字体?

更新时间:2023-11-15 12:35:22

供您参考,

 public class MyTextView extends TextView {

    public MyTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

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

    public MyTextView(Context context) {
        super(context);
        init();
    }

    public void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "font/yourfont.ttf");
        setTypeface(tf ,1);

    }
}

在XML中,

 <you_package.MyTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:textSize="20sp"
        android:text="Your text"
        />