Android 字體不隨系統字體變化

一、 APP字體大小,不隨系統的字體大小變化而變化的方法

1、將字體大小的單位設置了dp,就可以固定字體大小不隨系統設定的字號變化

sp和dp很類似但唯一的區別是,Android系統允許用戶自定義文字尺寸大小(小、正常、大、超大等等),當文字尺寸是“正常”時1sp=1dp=0.00625英寸,而當文字尺寸是“大”或“超大”時,1sp>1dp=0.00625英寸。

2、代碼設置(新)

● 新建類MyContextWrapper

 import android.content.Context;
 import android.content.ContextWrapper;
 import android.content.res.Configuration;
 import android.content.res.Resources;
 import android.os.Build;
 import android.support.annotation.NonNull;
 import android.util.DisplayMetrics;
 
 public class MyContextWrapper extends ContextWrapper { 
     public MyContextWrapper(Context base) {
         super(base);
     }
     @NonNull
     public static ContextWrapper wrap(Context context) {
         Resources resources = context.getResources();
         Configuration newConfig = new Configuration();
         DisplayMetrics metrics = resources.getDisplayMetrics();
         newConfig.setToDefaults();
         //如果沒有設置densityDpi, createConfigurationContext對字體大小設置限制無效
        newConfig.densityDpi = metrics.densityDpi;
         if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR1) {
             context = context.createConfigurationContext(newConfig);
         } else {
            resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
         }
        return new MyContextWrapper(context);
     }
 }
複製代碼

● 在所有Activity(BaseActivity)添加

@Override
 protected void attachBaseContext(Context newBase) {
     super.attachBaseContext(MyContextWrapper.wrap(newBase));
 }
複製代碼

updateConfiguration 設置會對其他Activity也有效。 createConfigurationContext 自對當前Activity有效。

3、代碼設置(過時)

1)在Application中加入

private void setTextDefault() {
     Resources res = super.getResources();
     Configuration config = new Configuration();
     config.setToDefaults();
     res.updateConfiguration(config, res.getDisplayMetrics());
 }
複製代碼

缺點:如果home出來,更改了字體大小,字體還是會改變。完全退出應用在進去,字體纔會改爲默認大小。

2)在所有Activity 中加入,改變字體大小能及時還原默認大小。

@Override
 public Resources getResources() {
  Resources resources = super.getResources();
  if (resources.getConfiguration().fontScale != 1) {
     Configuration newConfig = new Configuration();
     newConfig.setToDefaults();
     resources.updateConfiguration(newConfig, resources.getDisplayMetrics());
  }
  return resources;
 }
複製代碼

二、WebView 顯示html 字體大小不隨系統變化

webSettings.setTextZoom(100);//防止系統字體大小影響佈局

 

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