通过xml设置自定义字体

Vin*_*hwa 1 xml fonts android

如何设置一个字体,其ttf assets通过xml 驻留在我的文件夹中?我知道如何以编程方式执行此操作但是如何通过xml执行此操作?提前致谢.

Rag*_*hav 14

您无法直接使用XML,但您可以扩展TextView和设置默认字体.

package com.nannu;

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

public class NanTV extends TextView{

    private Context c;
    public NanTV(Context c) {
        super(c);
        this.c = c;
        Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                "font/yourfont.ttf");
        setTypeface(tfs);

    }
    public NanTV(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.c = context;
        Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                "font/yourfont.ttf");
        setTypeface(tfs);
        // TODO Auto-generated constructor stub
    }

    public NanTV(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.c = context;
        Typeface tfs = Typeface.createFromAsset(c.getAssets(),
                "font/yourfont.ttf");
        setTypeface(tfs);

    }


}
Run Code Online (Sandbox Code Playgroud)

在你的布局中使用new TextView

<com.nannu.NanTV
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" 

        />
Run Code Online (Sandbox Code Playgroud)

我是从我的热门答案/sf/answers/786751381/发布的