在Android的TextView中使用自定义字体,并使用xml自定义、字体、Android、TextView

2023-09-12 03:57:37 作者:不對你說謊

我添加了一个自定义的字体文件到我的资产/ fonts文件夹中。如何从我的XML使用它呢?

I have added a custom font file to my assets/fonts folder. How do I use it from my XML?

我可以如下使用它从code:

I can use it from code as follows:

TextView text = (TextView) findViewById(R.id.textview03);
Typeface tf = Typeface.createFromAsset(getAssets(), "fonts/Molot.otf");
text.setTypeface(tf);

我不能从XML使用安卓做到这一点:?字体=/字体/ Molot.otf属性

推荐答案

下面是例子code,这是否。我有一个静态的final变量和字体文件中定义的字体是在资产目录。

Here is example code that does this. I have the font defined in a static final variable and the font file is in the assets directory.

public class TextViewWithFont extends TextView {

    public TextViewWithFont(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setTypeface(MainActivity.typeface);
    }

    public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.setTypeface(MainActivity.typeface);
    }

    public TextViewWithFont(Context context) {
        super(context);
        this.setTypeface(MainActivity.typeface);
    }

}