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中,重寫getResources
和onConfigurationChanged
方法
@Override
public void onConfigurationChanged(Configuration newConfig) {
if (FontCompatUtils.shouldChangeFontScale(newConfig))
getResources();
super.onConfigurationChanged(newConfig);
}
@Override
public Resources getResources() {
return FontCompatUtils.getResources(super.getResources());
}
至此,我們就完成了字體大小的適配。
其他
更多適配方案,詳見聊聊 Android 中的字體大小適配
屏幕適配方案詳見 Android屏幕適配大全