【发布时间】:2016-10-07 09:59:57
【问题描述】:
我是 android 开发的新手,我需要为我编写的整个应用程序设置自定义字体:
public class TypeFaceUtil {
public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Map<String, Typeface> newMap = new HashMap<String, Typeface>();
newMap.put("SERIF", customFontTypeface);
try {
final Field staticField = Typeface.class
.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
} else {
try {
final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
defaultFontTypefaceField.setAccessible(true);
defaultFontTypefaceField.set(null, customFontTypeface);
} catch (Exception e) {
Log.e(TypeFaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}
}
我在应用程序类中这样称呼它:
public class tt extends Application {
@Override
public void onCreate() {
super.onCreate();
TypeFaceUtil.overrideFont(getApplicationContext(),"SERIF","fonts/calibri.ttf");
}
}
我的字体在棒棒糖或更高版本中不起作用,我也尝试过这种方法Custom Fonts not working in lollipop?如何创建支持所有版本的自定义字体提前感谢
【问题讨论】:
-
字体不会“工作”,除非您通过调用 textview、按钮或其他视图的 setTypeface() 方法来设置它们。
-
@M.Yogeshwaran 看到我的答案