本文正在参加「Java主题月 - Java Debug笔记活动」,详情查看<活动链接>
提问:是否可以为整个应用程序设置自定义字体?
我需要为整个应用程序使用某些字体。我有所需的.ttf文件。是否可以在应用程序启动时将此字体设置为默认字体,然后在应用程序中的其他位置使用它?设置后,如何在布局XML中使用它?
回答1:
是的,由于缺乏对自定义字体的支持,因此这是一种解决方法。
import java.lang.reflect.Field;
import android.content.Context;
import android.graphics.Typeface;
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");
}
}
或者如果您使用的是相同的字体文件,则可以对此进行改进以仅将其加载一次。但是,我倾向于只覆盖一个,比如说"MONOSPACE",然后设置一种样式来强制该字体应用程序在整个应用程序中使用:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
API 21 Android5.0与上述代码并不能很好兼容。