是的,有反思。这有效(基于这个答案):
(注意:这是由于缺乏对自定义字体的支持而采取的解决方法,因此如果您想改变这种情况,请加注星标安卓问题在这里). Note:不要在这个问题上留下“我也是”的评论,当你这样做时,每个关注过它的人都会收到一封电子邮件。所以请给它“加注星标”。
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();
}
}
}
然后,您需要重载一些默认字体,例如在应用 class:
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 安卓 5.0
我调查了评论中的报告,认为它不起作用并且似乎与主题不兼容android:Theme.Material.Light
.
如果该主题对您来说不重要,请使用较旧的主题,例如:
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>