Android 解决字体随系统调节而变化的问题

  • 看了标题也许不太清楚,所以先上两张 滴滴 的截图,对比一下:

1.png.jpeg

2.png.jpeg


应该可以明显的看到,第一张图中红色框中的“分钟”两个字显示不完整,原因就是:1、用户在设置中调节了字体大小,2、红色框布局中TextView使用的是单位为“sp”,并且布局宽高也是固定的。

  • 在这里引入一个知识点:关于sp文档的描述为:

    Scale-independent Pixels – This is like the dp unit, but it is also scaled by 
    the user’s font size preference. It is recommend you use this unit when 
    specifying font sizes, so they will be adjusted for both the screen density
    and the user’s preference.

    Android sp单位除了受屏幕密度影响外,还受到用户的字体大小影响,通常情况下,建议使用sp来跟随用户字体大小设置。除非一些特殊的情况,不想跟随系统字体变化的,可以使用dp”。按照这么说,布局宽高固定写死的地方应该统一用dp显示字体,因为一旦用户在设置中调大字体,宽高写死的布局显示就乱了。

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

    • 同样的布局代码
    <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" />
    • 调节设置中显示字体大小


      4.png.jpeg

    • 运行后显示样式


      3.png.jpeg

    3、好了,回到标题要解决的问题,如果要像微信一样,所有字体都不允许随系统调节而发生大小变化,要怎么办呢?利用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;
    }

    4、总结,两种方案解决这个问题:
    一是布局宽高固定的情况下,字体单位改用dp表示;
    二是通过3中的代码设置应用不能随系统调节,在检测到fontScale属性不为默认值1的情况下,强行进行改变。

    如有问题,还望提出意见,毕竟个人经验有限。

    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章