700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > Android 中的字体大小适配

Android 中的字体大小适配

时间:2019-02-03 17:47:36

相关推荐

Android 中的字体大小适配

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();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屏幕适配大全

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。