无法重置或替换 Android 应用程序中的默认字体

Cannot reset or replace default font in the Android application

我在我的应用程序中设置了默认字体,现在我认为它不适合 UI,我想重新设置它。但是不知道怎么重置。

这是代码,我们将不胜感激这个问题的解决方案。

(1) 我首先创建了一个 FontOverride class 来用新字体替换默认字体。

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

(2) 我创建了另一个名为 AppConfig 的 class,它控制应用程序的整体配置。

    public class AppConfig extends android.app.Application {

    public static String URL_LOGIN = "http://marshall.hostzi.com/Gruppo/";
    public static String URL_REGISTER = "http://marshall.hostzi.com/Gruppo/";

    @Override
    public void onCreate() {
        super.onCreate();
        FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/Galderglynn.ttf");
    }
}

(3) 最后是 style.xml 文件。有一个名为 monospace 的项目,因此 monospace 将以编程方式替换为 Ganderglynn.ttf。

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:typeface">monospace</item>
</style>

我尝试用另一个文件切换 Galderglynn.ttf 文件,但它不起作用,字体仍然是 Galderglynn 字体。

编辑这里是 Androidmanifest.xml 文件的一部分。

<application
    android:name="com.marshall.gruppo.app.AppController"
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

我认为你需要在 yourapp/src/main/assets/fonts/ 中添加另一种字体 像这样:(抱歉,我现在不能 post 图片)

下一步,更改配置中的 fontPath

public class AppConfig extends android.app.Application {

    public static String URL_LOGIN = "http://marshall.hostzi.com/Gruppo/";
    public static String URL_REGISTER = "http://marshall.hostzi.com/Gruppo/";

    @Override
    public void onCreate() {
        super.onCreate();
        FontsOverride.setDefaultFont(this, "MONOSPACE", "fonts/HelveticaNeue.ttf");
    }
}

最后,我推荐一些很棒的库来更改默认字体,例如 Calligraphy:https://github.com/chrisjenx/Calligraphy