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

时间:2015-07-11 11:59:22

标签: android android-typeface

我在我的应用程序上设置了默认字体,现在我认为它不适合用户界面,我想重置它。但我不知道如何重置它。

以下是代码,我们将非常感谢您解决此问题。

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

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的类来控制应用程序的整体配置。

    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" >

1 个答案:

答案 0 :(得分:0)

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

接下来的步骤,在config

中更改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");
    }
}

最后,我建议使用一些很棒的库来更改书法的默认字体:https://github.com/chrisjenx/Calligraphy