2022-10-15 字體不隨系統(tǒng)的字體大小變化而變化

一、 APP字體大小,不隨系統(tǒng)的字體大小變化而變化的方法

1、將字體大小的單位設(shè)置了dp,就可以固定字體大小不隨系統(tǒng)設(shè)定的字號(hào)變化

sp和dp很類(lèi)似但唯一的區(qū)別是,Android系統(tǒng)允許用戶自定義文字尺寸大小(小、正常、大、超大等等),當(dāng)文字尺寸是“正?!睍r(shí)1sp=1dp=0.00625英寸,而當(dāng)文字尺寸是“大”或“超大”時(shí),1sp>1dp=0.00625英寸。

2、代碼設(shè)置(新)

● 新建類(lèi)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(); //如果沒(méi)有設(shè)置densityDpi, createConfigurationContext對(duì)字體大小設(shè)置限制無(wú)效 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 設(shè)置會(huì)對(duì)其他Activity也有效。

createConfigurationContext 自對(duì)當(dāng)前Activity有效。

3、代碼設(shè)置(過(guò)時(shí))

1)在Application中加入

private void setTextDefault() {

private void setTextDefault() {?

?Resourcesres= super.getResources();

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

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

}

缺點(diǎn):如果home出來(lái),更改了字體大小,字體還是會(huì)改變。完全退出應(yīng)用在進(jìn)去,字體才會(huì)改為默認(rèn)大小。

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

@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 字體大小不隨系統(tǒng)變化

webSettings.setTextZoom(100);//防止系統(tǒng)字體大小影響布局

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容