美文网首页
2022-10-15 字体不随系统的字体大小变化而变化

2022-10-15 字体不随系统的字体大小变化而变化

作者: 王培921223 | 来源:发表于2022-10-15 11:08 被阅读0次

    一、 APP字体大小,不随系统的字体大小变化而变化的方法

    1、将字体大小的单位设置了dp,就可以固定字体大小不随系统设定的字号变化

    sp和dp很类似但唯一的区别是,Android系统允许用户自定义文字尺寸大小(小、正常、大、超大等等),当文字尺寸是“正常”时1sp=1dp=0.00625英寸,而当文字尺寸是“大”或“超大”时,1sp>1dp=0.00625英寸。

    2、代码设置(新)

    ● 新建类MyContextWrapper

    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() {

    private void setTextDefault() { 

     Resourcesres= super.getResources();

    Configurationconfig= new Configuration();config.setToDefaults();

    res.updateConfiguration(config, res.getDisplayMetrics());

    }

    缺点:如果home出来,更改了字体大小,字体还是会改变。完全退出应用在进去,字体才会改为默认大小。

    2)在所有Activity 中加入,改变字体大小能及时还原默认大小。

    @Override public Resources getResources() {  

    Resourcesresources= super.getResources();

    if (resources.getConfiguration().fontScale != 1) { 

       ConfigurationnewConfig= new Configuration();

    newConfig.setToDefaults();

    resources.updateConfiguration(newConfig, resources.getDisplayMetrics());

    }  

    return resources;

    }

    二、WebView 显示html 字体大小不随系统变化

    webSettings.setTextZoom(100);//防止系统字体大小影响布局

    相关文章

      网友评论

          本文标题:2022-10-15 字体不随系统的字体大小变化而变化

          本文链接:https://www.haomeiwen.com/subject/davhzrtx.html