繁体   English   中英

如何在Android中为整个应用程序设置自定义字体

[英]How to set a custom font for the entire application in Android

好的,所以我对此进行了研究,发现了一些与该主题相关的代码,但是当我尝试时似乎不起作用。 我不得不分别更改每个文本视图的字体,这让我发疯。 到目前为止,我所做的是创建一个将覆盖字体的类:

public final class FontsOverride {

public static void setDefaultFont(Context context,
                                  String staticTypefaceFieldName, String fontAssetName) {
    final Typeface regular = Typeface.createFromAsset(context.getAssets(),
            fontAssetName);
    replaceFont(staticTypefaceFieldName, regular);
}

protected static void replaceFont(String staticTypefaceFieldName,
                                  final Typeface newTypeface) {
    try {
        final Field staticField = Typeface.class
                .getDeclaredField(staticTypefaceFieldName);
        staticField.setAccessible(true);
        staticField.set(null, newTypeface);
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}
}

然后,每次我希望覆盖每个类中的字体时,我都会试图暗示这一点:

   FontsOverride.setDefaultFont(this, "DEFAULT", "ComicRelief.ttf");

必须有一种简单的方法来执行此操作,而我已经尝试了好几个小时,但仍无法解决。

只需创建一个自定义TextView类:

public class CustomTextView extends TextView {

    public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        load();
    }

    public CustomTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        load();
    }

    public CustomTextView(Context context) {
        super(context);
        load();
    }

    public void load() {
        setTypeface(
            Typeface.createFromAsset(getContext().getAssets(), "pacifico.ttf"), 1
        );
    }

}

将自定义视图应用于所需的任何TextView:

<com.your.package.views.CustomTextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

现在已声明您的TextView类型并将其强制转换为CustomTextView:

CustomTextView myTextView = (CustomTextView) findViewById(R.id.my_text_view);

并记住将适当的字体放入资产文件夹中(在本示例中为“ pacifico.ttf”)。

您需要使用书法库为整个应用程序设置自定义字体。

在您的自定义Application类中,在onCreate()内初始化Calligraphy:

CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                        .setDefaultFontPath("fonts/custom_font.ttf")
                        .setFontAttrId(R.attr.fontPath)
                        .build());

在这里, custom_font.ttf是您要应用于整个应用程序的字体,它需要驻留在assets/fonts文件夹中。

其次,您需要重写Activity类中的attachBaseContext()方法,如下所示:

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
}

现在,您在应用程序中看到的每个文本都具有您通过书法设置为默认字体的字体。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM