Android 自定义字体大小、显示大小、语言(不跟随系统)简单
2023-04-23 本文已影响0人
可乐_JS
1.直接上代码,先新建一个工具类
public class ConfigurationUtil {
private static final String TAG = "ConfigurationUtil";
public static final float DEFAULT_FONT_SCALE = 1.0f;
/**
* 更新configuration
*
* @param res 资源
* @return
*/
@NonNull
public static Resources updateConfiguration(Context context, Resources res) {
Configuration configuration = res.getConfiguration();
//设置字体大小
float fontScale = configuration.fontScale;
if (!SizeUtil.isFloatValueEquals(fontScale, DEFAULT_FONT_SCALE)) {
Log.i(TAG, "updateConfiguration reset fontScale = " + fontScale);
configuration.fontScale = DEFAULT_FONT_SCALE;
}
//设置dpi
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
int densityDpi = configuration.densityDpi;
if (densityDpi != DisplayMetrics.DENSITY_DEVICE_STABLE) {
Log.i(TAG, "updateConfiguration reset densityDpi = " + densityDpi);
Log.i(TAG, "updateConfiguration DENSITY_DEVICE_STABLE = " + DisplayMetrics.DENSITY_DEVICE_STABLE);
configuration.densityDpi = DisplayMetrics.DENSITY_DEVICE_STABLE;
}
}
//设置语言
boolean isEnglish = context == null ? false : MyApplicationUtils.readBooleanConfig(context, GlobalKeys.CURRENT_IS_ENGLISH);
Locale locale = isEnglish ? Locale.ENGLISH : Locale.SIMPLIFIED_CHINESE;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
configuration.setLocale(locale);
} else {
configuration.locale = locale;
}
res.updateConfiguration(configuration, res.getDisplayMetrics());
return res;
}
}
2.再分别在Application和BaseActivity中重写geResources,即可。
@Override
public Resources getResources() {
Resources res = super.getResources();
return ConfigurationUtil.updateConfiguration(this, res);
}
截屏2023-04-24 14.06.54.png之所以要重写Application和Activity的原因如下