gpt4 book ai didi

java - 防止自定义系统字体覆盖应用程序字体

转载 作者:行者123 更新时间:2023-12-02 01:18:17 25 4
gpt4 key购买 nike

三星等设备允许用户设置自定义系统字体。问题是这些字体可能会覆盖我的应用字体。我的意思是,如果我在应用程序中设置 Arial font 并且在我的应用程序中将 Calibri 字体设置为 system font如果是移动设备,则 Arial 将被 Calibri 字体 覆盖。

如何防止这种情况发生?

最佳答案

  • "If you need to set one font for all TextView's in your Android application you can use this solution.
  • It will override ALL TextView's typefaces, including the Action Bar, custom system fonts and other standard components, but EditText's password font won't be overridden." (For obvious reasons).

  • Using reflection to override default typeface and the Application 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:

您的字体放在这里,例如宋体

ref1

作者Artem Zinnatullin

关于java - 防止自定义系统字体覆盖应用程序字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58196498/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com