如何将整个应用程序的可下载字体设置为默认字体?

问题描述 投票:1回答:3

在我之前的项目中,我使用Calligraphy库为整个应用程序设置字体。但它需要在资产中存储字体文件,这会使APK大小更大。现在我想知道是否可以将downloadable font设置为整个应用程序的默认值。

我只能为一个TextView设置一个可下载的字体。

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="@dimen/text_margin"
    android:fontFamily="@font/lato"
    android:text="@string/large_text" />

是的,我知道我可以创建MyTextView类并以编程方式设置可下载的字体。但我不认为这是一个好主意,因为文本可以在EditText,Spinner项目,Toast中的任何位置。

所以我的问题是如何将整个应用程序的可下载字体设置为默认字体?

android android-fonts android-downloadable-fonts
3个回答
1
投票

要在应用程序的任何位置应用XML字体集,请在themes.xml中创建主题并在其中设置android:fontFamily

<style name="ApplicationTheme">
    <item name="android:fontFamily">@font/lato</item>
</style>

将此主题设置为Manifest中的应用程序

<application
    android:name=".App"
    android:icon="@mipmap/ic_launcher"
    android:theme="@style/ApplicationTheme">
...
</application>

并且只要您不使用继承自系统样式的样式

<style name="CustomButton" parent="Base.Widget.AppCompat.Button.Borderless">

您的字体将应用于所有TextViews,EditTexts,Spinners,Toast等。


0
投票

A library to help with custom fonts and text sizes

此库的目标是允许您的应用程序以一种易于配置的方式支持多种FontFamilies(例如lato,roboto等)及其自己的样式(例如,普通,粗体,斜体)。


0
投票
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");
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.