三星等设备允许用户设置自定义系统字体
。问题是这些字体可能会覆盖我的应用字体
。我的意思是,如果我在应用程序中设置 Arial
font
并且在我的应用程序中将 Calibri
字体设置为 system font
如果是移动设备,则 Arial
将被 Calibri 字体
覆盖。
如何防止这种情况发生?
最佳答案
- "If you need to set one font for all
TextView's
in yourAndroid
application you can use this solution.It will override ALL
TextView's
typefaces, including theAction Bar
, custom system fonts and other standard components, butEditText's
password font won't be overridden." (For obvious reasons).Using
reflection
to override default typeface and theApplication
class.- NOTE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
MyApp.java:
public class MyApp extends Application {
@Override
public void onCreate() {
TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/Roboto-Regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf
}
}
res/themes.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="MyAppTheme" parent="@android:style/Theme.Holo.Light">
<!-- you should set typeface which you want to override with TypefaceUtil -->
<item name="android:typeface">serif</item>
</style>
</resources>
TypefaceUtil.java:
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import java.lang.reflect.Field;
public class TypefaceUtil {
/**
* Using reflection to override default typeface
* NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
* @param context to work with assets
* @param defaultFontNameToOverride for example "monospace"
* @param customFontFileNameInAssets file name of the font from assets
*/
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("Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
}
}
}
assets/fonts/Roboto-Regular.ttf:
将您的字体放在这里,例如宋体
。
关于java - 防止自定义系统字体覆盖应用程序字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58196498/