Android - 如何在xml中设置家族字体“noto sans”?

3

我正在开发一个针对Lollipop(Android 5.0)以上版本用户的Android小部件应用。

由于某些原因,我必须在我的应用程序中使用一种名为“noto sans”(https://www.google.com/get/noto/#/)的字体。

我听说它包含在Lollipop中,但我不知道如何在xml中使用它。

有人知道吗?

2个回答

0

不可以在布局文件(XML)中使用自定义字体。您必须像下面展示的那样在程序中使用自定义字体。

String fontPath = "fonts/calibrib.ttf";

          // Loading Font Face
          Typeface tf = Typeface.createFromAsset(mContext.getAssets(), fontPath);

TextView txtView = new TextView(this);
txtView.setTypeface(tf);

将您的字体放置在资产文件夹中。以下是上述代码起作用的原因。

enter image description here


0
你可以通过重写 TextView 来创建自己的 TextView,像这样,你必须将字体放在 assets 文件夹中:
public class MyTextView extends TextView {

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

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

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

    private void setType(Context context){
        this.setTypeface(Typeface.createFromAsset(context.getAssets(),
                    "foo.ttf"));

        this.setShadowLayer(1.5f, 5, 5, getContext().getResources().getColor(R.color.black_shadow));
    }
}

使用方法如下:

<com.your.project.package.MyTextView
        android:id="@+id/oppinfo_mtv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"  
        android:text="Player 1"
        />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接