如何在android xml中使用自定义字体?

Vin*_*ins 25 android textview android-layout

如何使用我的xml资产文件夹中添加的自定义字体?我知道我们可以setTypeface()在java中使用方法,但我们必须在我们使用它的地方执行此操作TextView.那么还有更好的方法吗?

Vin*_*ins 58

我通过Google搜索找到的最佳方式是 - 如果你想在TextView中使用,那么我们必须扩展Textview并且必须设置字体,以后我们可以在我们的xml中使用我们的自定义Textview.我将在下面显示扩展的TextView

package com.vins.test;

import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

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();
    }

    private void init() {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(),
                                               "your_font.ttf");
        setTypeface(tf);
    }

}
Run Code Online (Sandbox Code Playgroud)

我们调用init()来设置每个协处理器中的字体.稍后我们必须在main.xml中使用它,如下所示.

<com.vins.test.MyTextView
    android:id="@+id/txt"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:layout_weight="1"
    android:text="This is a text view with the font u had set in MyTextView class "
    android:textSize="30dip"
    android:textColor="#ff0000"
   >
Run Code Online (Sandbox Code Playgroud)

更新:

请注意pandre提到的4.0之前的Android内存泄漏.

  • 请注意,此解决方案会导致较旧的Android版本中出现内存泄漏.通过缓存创建的字体来避免这种情况.更多信息:https://code.google.com/p/android/issues/detail?id = 9994 (4认同)