是否有可能设置字体为整个应用程序?有可能、应用程序、字体

2023-09-12 00:03:16 作者:心若浮沉,浅笑安然

我需要使用特定的字体我的整个应用程序。我已经.TTF文件为同一。 是否有可能将此设置为默认字体,在应用程序启动,然后在应用程序中的其他地方使用它?当设置,我如何使用它在我的布局XMLS?

I need to use certain font for my entire application. I have .ttf file for the same. Is it possible to set this as default font, at application start up and then use it elsewhere in the application? When set, how do i use it in my layout XMLs?

样品code,教程,可以帮助我在这里是AP preciated。

Sample code, tutorial that can help me here is appreciated.

感谢。

推荐答案

是与反思。这工作(在此基础上回答 ):

Yes with reflection. This works (based on this answer):

import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;

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

然后你需要重载几个默认字体,例如在应用类:

public final class Application extends android.app.Application {
    @Override
    public void onCreate() {
        super.onCreate();
        FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
        FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
        FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
        FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
    }
}

或者,当然,如果你使用的是相同的字体文件,可以提高这个来加载一次。

Or course if you are using the same font file, you can improve on this to load it just once.

不过,我倾向于只覆盖一个,说MONOSPACE,然后建立一个样式,迫使该字体的字体应用广泛:

However I tend to just override one, say "MONOSPACE", then set up a style to force that font typeface application wide:

<resources>
    <style name="AppBaseTheme" parent="android:Theme.Light">
    </style>

    <!-- Application theme. -->
    <style name="AppTheme" parent="AppBaseTheme">
        <item name="android:typeface">monospace</item>
    </style>
</resources>

API 21的Andr​​oid 5.0

我已经调查报告中评论说,这是行不通的,它似乎与主题的Andr​​oid不兼容:Theme.Material.Light

如果说主题是对你并不重要,使用旧的主题,如:

If that theme is not important to you, use an older theme, e.g.:

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
    <item name="android:typeface">monospace</item>
</style>