Android 禁止App字体随系统大小而更改

运营反馈,老年用户的手机多设置为大字体,在使用我们app过程中,由于字体被放大,导致布局错乱,部分功能按键遮挡,无法正常使用。

收到问题,着手解决,除了对界面布局进行改写,改为约束布局,对app字体大小也进行统一管理,然而这不是主要的,最主要的是避免系统更改app字体的大小。

Android提供了相关的方法用来实现

复制代码
 public class DisplayUtil {
        /**
         * 保持字体大小不随系统设置变化(用在界面加载之前)
         * 要重写Activity的attachBaseContext()
         */
        public static Context attachBaseContext(Context context, float fontScale) {
            Configuration config = context.getResources().getConfiguration();
            //正确写法
            config.fontScale = fontScale;
            return context.createConfigurationContext(config);
        }

        /**
         * 保持字体大小不随系统设置变化(用在界面加载之前)
         * 要重写Activity的getResources()
         */
        public static Resources getResources(Context context, Resources resources, float fontScale) {
            Configuration config = resources.getConfiguration();
            if(config.fontScale != fontScale) {
                config.fontScale = fontScale;
                return context.createConfigurationContext(config).getResources();
            } else {
                return resources;
            }
        }

        /**
         * 保存字体大小,后通知界面重建,它会触发attachBaseContext,来改变字号
         */
        public static void recreate(Activity activity) {
            activity.recreate();
        }
}

在BaseActivity中复写相关的方法:

复制代码
 static float fontScale = 1f;

    @Override
    public Resources getResources() {
        Resources resources = super.getResources();
        return DisplayUtil.getResources(this,resources,fontScale);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(DisplayUtil.attachBaseContext(newBase,fontScale));
    }
    
    public void setFontScale(float fontScale) {
        this.fontScale = fontScale;
        DisplayUtil.recreate(this);
    }

经测试,在设置中把字体调整为最大,打开app,app中字体均保持不变,测试华为,vivo,小米机型均生效,于是交付测试。

相关推荐
2601_9498095937 分钟前
flutter_for_openharmony家庭相册app实战+通知设置实现
android·javascript·flutter
液态不合群1 小时前
【面试题】MySQL 中 count(*)、count(1) 和 count(字段名) 有什么区别?
android·数据库·mysql
雪球Snowball3 小时前
【Android关键流程】资源加载
android
2501_915918413 小时前
常见 iOS 抓包工具的使用,从代理抓包、设备抓包到数据流抓包
android·ios·小程序·https·uni-app·iphone·webview
墨月白4 小时前
[QT]QProcess的相关使用
android·开发语言·qt
enbug5 小时前
编译安卓内核:以坚果R1、魔趣MK100(Android 10)系统为例
android·linux
、BeYourself5 小时前
应用专属文件与应用偏好设置(SharedPreferences)
android
2501_948120155 小时前
基于模糊数学的风险评估模型
android
MengFly_6 小时前
Compose 脚手架 Scaffold 完全指南
android·java·数据库
·云扬·6 小时前
MySQL Binlog三种记录格式详解
android·数据库·mysql