Android系统中可以设置字体大小,对于一些设置了特大号字体的设备,往往会出现布局错乱的情况,对此,需要做相关的字体大小适配。根据聊聊 Android 中的字体大小适配这篇博客提供的方案,进行了一些改进,找到了一种比较合适的方式,将字体大小控制在合理范围内。

已MIUI为例,系统中设置的字体大小对应的fontScale如下

巨无霸 1.4超大 1.4大号 1.32中号 1.15标准 1小号 0.86

小号字体下,会比较精致,不作处理。对于大号字体,使其fontScale强制改为指定值,以解决布局错乱的情况。
封装为工具类如下

public class FontCompatUtils {    public static final float MAX_FONT_SCALE = 1.10F; //可自行修改最大缩放值    public static final String TAG = "FontCompatUtils";    private static Float fontScalePercent = null;    public static Resources getResources(Resources res) {        Configuration configuration = res.getConfiguration();        Log.i(TAG, "getResources fontScale:" + configuration.fontScale);        if (fontScalePercent == null) {            fontScalePercent = 1 / configuration.fontScale;        }        if (shouldChangeFontScale(configuration)) {//非默认值            Configuration newConfig = new Configuration();            //newConfig.setToDefaults();//设置默认            configuration.fontScale = MAX_FONT_SCALE;            res.updateConfiguration(newConfig, res.getDisplayMetrics());        }        return res;    }    /**     * 是否需要改变字体缩放级别     *     * @param configuration     * @return     */    public static boolean shouldChangeFontScale(Configuration configuration) {        return configuration.fontScale > MAX_FONT_SCALE;    }    /**     * 字体缩放比例     *     * @return     */    public static Float getFontScalePercent() {        if (fontScalePercent == null) {            return 1F;        }        return fontScalePercent;    }}

然后,在Application和BaseActivity中,重写getResourcesonConfigurationChanged方法

@Overridepublic void onConfigurationChanged(Configuration newConfig) {    if (FontCompatUtils.shouldChangeFontScale(newConfig))        getResources();    super.onConfigurationChanged(newConfig);}@Overridepublic Resources getResources() {    return FontCompatUtils.getResources(super.getResources());}

至此,我们就完成了字体大小的适配。

其他

更多适配方案,详见聊聊 Android 中的字体大小适配
屏幕适配方案详见 Android屏幕适配大全

更多相关文章

  1. Android使用selector修改TextView中字体颜色和背景色的方法
  2. android 自定义view之选座功能
  3. Android之Matrix用法
  4. Android中进行图像压缩和缩放
  5. Android(安卓)Matrix 介绍
  6. [Android]解决Window系统adb shell后中文显示乱码
  7. android平台yuv缩放相关
  8. Android(安卓)修改全局自定义字体样式(字形,大小)※
  9. android studio ——使用as前的基本设置(很实用的as设置)

随机推荐

  1. Android如何实时监听网络状态.
  2. Android:实现装备购买
  3. android 数据报表
  4. android p IntentService有关stopSelf
  5. Android实现音量调节的方法
  6. 自用连接:android经典教程,软件开发,项目管
  7. Android(安卓)UI设计 时间控件TimePicker
  8. android http通信(一) HttpURLConntectio
  9. android手势
  10. Android不常用代码(1)