Android 字体适配方案

开发过程中,按照UI设计尺寸做好UI页面,当用户自定义自己的手机字体大小之后UI完全没法看了,这个时候就在想让app字体大小始终一致就好了
下面看一下,出现的问题和解决方案
 
 

做个简单的例子,先验证一下:

同样的布局代码

<TextView   
 android:layout_width="wrap_content"    
 android:layout_height="wrap_content"   
 android:textSize="18sp"    
 android:text="Hello World! in SP" />

<TextView  
 android:layout_width="wrap_content"    
 android:layout_height="wrap_content" 
 android:textSize="18dp"    
 android:text="Hello World! in DP" />

调节设置中显示字体大小

运行后显示样式

回到标题要解决的问题,如果要像微信一样,所有字体都不允许随系统调节而发生大小变化,要怎么办呢?利用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.setToDefaults();//设置默认
res.updateConfiguration(newConfig, res.getDisplayMetrics());
}
return res;
}

总结:

一是布局宽高固定的情况下,字体单位改用dp表示;

注意,如果使用的sp,还是会随用户的字体大小的改变而改变,所以这里使用dp设置

二是通过3中的代码设置应用不能随系统调节,在检测到fontScale属性不为默认值1的情况下,强行进行改变。



 
 
原文地址:https://www.cnblogs.com/dingxiansen/p/9883085.html