禁止跟随系统字体大小调节
如果要像微信一样,所有字体都不允许随系统调节而发生大小变化,要怎么办呢?利用Android的Configuration类中的fontScale属性,其默认值为1,会随系统调节字体大小而发生变化,如果我们强制让其等于默认值,就可以实现字体不随调节改变,在工程的Application或BaseActivity中添加下面的代码:
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (newConfig.fontScale != 1)//非默认值
getResources();
super.onConfigurationChanged(newConfig);
}
@Override
public Resources getResources() {
Resources res = super.getResources();
if (res.getConfiguration().fontScale != 1) {//非默认值
Configuration newConfig = new Configuration();
//newConfig.fontScale = 1;//字体重置为1
newConfig.setToDefaults();//设置默认
res.updateConfiguration(newConfig, res.getDisplayMetrics());
}
return res;
}
应用全局字体大小调节
在Application中复写getResources()方法
@Override
public Resources getResources() {//还原字体大小
Resources res = super.getResources();
Configuration configuration = res.getConfiguration();
if (configuration.fontScale != fontScale) {//fontScale要缩放的比例
configuration.fontScale = fontScale;
res.updateConfiguration(configuration, res.getDisplayMetrics());
}
return res;
}
Android 8.0适配
Android 8.0上会发现这样修改字体的缩放比例是不起作用的,
需要在Activity中同样进行复写getResources()方法。
整个应用字体大小调节方案
在设置界面进行字体缩放比例调节,退出时关闭所有已打开的Activity,并重启主界面。
@Override
public void onBackPressed() {
saveFontScaleRate();
}
private void saveFontScaleRate() {
if (defaultFontScaleRate != fontScaleRate) {
new SpUtils(FontScaleActivity.this).putData(ICourtApplication.FONT_SCALE_RATE, fontScaleRate);
BaseApplication.setFontScale(fontScaleRate);
AppManager appManager = AppManager.getAppManager();
MainActivity activity = appManager.getActivity(MainActivity.class);
appManager.finishAllActivity(activity);
activity.recreate();
} else {
finish();
}
}
注意
所有想要缩放的控件,不只是TextView,任何控件,只需要将尺寸单位换成SP,
自然,不想要随字体调节改变的也只需将SP换成其他单位。