java – 无法在Android应用中更改默认字体

前端之家收集整理的这篇文章主要介绍了java – 无法在Android应用中更改默认字体前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试更改我的应用程序中的默认字体.但它不起作用.这些是我采取的步骤:

1)创建类TypefaceUtil.java

import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;

import java.lang.reflect.Field;

public class TypefaceUtil {

public static void overrideFont(Context context,String defaultFontNameToOverride,String customFontFileNameInAssets) {
    try {
        final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(),customFontFileNameInAssets);

        final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
        defaultFontTypefaceField.setAccessible(true);
        defaultFontTypefaceField.set(null,customFontTypeface);
    } catch (Exception e) {
        Log.e("CustomFontException","Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
    }
  }
}

2)在扩展应用程序的类中:

public void onCreate() {

     super.onCreate();
     TypefaceUtil.overrideFont(getApplicationContext(),"MONOSPACE","fonts/varelaround_regular.ttf");
 }

3)在styles.xml中