Skip to content

Latest commit

 

History

History
57 lines (43 loc) · 2.26 KB

解决字体适配.md

File metadata and controls

57 lines (43 loc) · 2.26 KB

img

img

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

同样的布局代码

<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" />

调节设置中显示字体大小

img

运行后显示样式

img

回到标题要解决的问题,如果要像微信一样,所有字体都不允许随系统调节而发生大小变化,要怎么办呢?利用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表示; 二是通过3中的代码设置应用不能随系统调节,在检测到fontScale属性不为默认值1的情况下,强行进行改变。