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

标签 java android android-studio

三星等设备允许用户设置自定义系统字体。问题是这些字体可能会覆盖我的应用字体。我的意思是,如果我在应用程序中设置 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/

相关文章:

java - scrollPathToVisible 行为不正常

java - 如何更改默认保存在 .camel 子目录中的文件的位置

android - Android中如何通过扩展View来拖动多张图片?

android - 从 Android Studio 的构建中排除一个类

java - Sonar 在哪里检查记录的 Api 配置

Java:WAITING所有子进程完成

android - 一项 Activity 或单独 Activity 中的多个 fragment

java - 使用适用于 Android 的新 Facebook SDK 将内容添加到 Facebook 提要对话框

java - 在 android 中测试 Color 类没有按预期工作

Android Studio 重复文件