能否为整个应用设置自定义字体?

275

我需要在整个应用程序中使用某种特定字体。我有相应的.ttf文件。 是否可以在应用程序启动时将其设置为默认字体,然后在应用程序的其他地方使用它?设置后,我该如何在我的布局XML中使用它?


在Android Studio 3.0中,您可以轻松设置自定义字体:https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml - MHSaffari
@MHSFisher 字体在 XML 中是 Android 8.0(API 级别 26)的一个功能。 - Emad Razavi
1
@EmiRaz 请阅读文档 https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml#using-support-lib。该功能已添加到支持库26中,但支持API 16及以上版本。 - MHSaffari
25个回答

0
package com.theeasylearn.demo.designdemo;
import android.content.Context;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

public class MyButton extends TextView {

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

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

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

    private void init() {

            Typeface tf =
                    Typeface.createFromAsset(
                            getContext().getAssets(), "angelina.TTF");
            setTypeface(tf);

    }

}

不是完美的解决方案。使用此解决方案将需要定制的解决方法来访问默认的Android TextView - blueware

0

0

-1

-15

是的,可以将字体设置为整个应用程序。

最简单的方法是将所需的字体与应用程序一起打包。

要做到这一点,只需在项目根目录中创建一个assets/文件夹,并将字体(以TrueType或TTF形式)放入其中。

例如,您可以创建assets/fonts/并将TTF文件放在其中。

public class FontSampler extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
TextView tv=(TextView)findViewById(R.id.custom);

Typeface face=Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
tv.setTypeface(face);
}
}

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