更新时间:2023-10-16 08:24:58
是的,有反射.这有效(基于此答案):
Yes with reflection. This works (based on this answer):
(注意:由于缺乏对自定义字体的支持,这是一种解决方法,所以如果你想改变这种情况,请为 android 问题在这里).注意:不要在这个问题上留下我也是"的评论,当你这样做时,所有关注它的人都会收到一封电子邮件.所以请给它加星标".
(Note: this is a workaround due to lack of support for custom fonts, so if you want to change this situation please do star to up-vote the android issue here). Note: Do not leave "me too" comments on that issue, everyone who has stared it gets an email when you do that. So just "star" it please.
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();
}
}
}
然后您需要重载少数默认字体,例如在应用程序 类:
You then need to overload the few default fonts, for example in an application 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");
}
}
当然,如果您使用相同的字体文件,您可以改进它以仅加载一次.
Or course if you are using the same font file, you can improve on this to load it just once.
但是我倾向于只覆盖一个,比如 "MONOSPACE"
,然后设置一个样式来强制该字体字体应用广泛:
However I tend to just override one, say "MONOSPACE"
, then set up a style to force that font typeface application wide:
<resources>
<style name="AppBaseTheme" parent="android:Theme.Light">
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<item name="android:typeface">monospace</item>
</style>
</resources>
我已经调查了评论中的报告,它不起作用并且它似乎与主题 android:Theme.Material.Light
不兼容.
如果该主题对您不重要,请使用较旧的主题,例如:
If that theme is not important to you, use an older theme, e.g.:
<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
<item name="android:typeface">monospace</item>
</style>