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的情況下,強行進行改變。

    如有問題,還望提出意見,畢竟個人經驗有限。

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