兩種方法避免系統更改字型大小
阿新 • • 發佈:2018-12-16
當用戶更改系統的字型大小後,App介面可能會變得面目全非,適配起來非常困難。 有的時候我們可能不需要去適配,那麼就需要限制部分頁面或者控制元件受系統字型大小更改的影響。
目前,大家在網上搜,一般都是下面的這個辦法,這也是今天介紹的第一個方法,可以直接使當前Activity的所有字型大小固定:
@Override
public Resources getResources() {
Resources resources = super.getResources();
if (resources != null) {
Configuration configuration = resources.getConfiguration();
// 系統設定的字型大小超過了我們接受的限制
if (configuration != null && configuration.fontScale > mLimitFontScale) {
configuration.fontScale = mLimitFontScale; // 強制設定為自己想要的放大倍數
resources.updateConfiguration(configuration, resources.getDisplayMetrics ());
}
}
return resources;
}
這種方式主要是重寫系統的getResources方法,來強制更新fontScale的值。但這個方法有個缺點,即會影響當前Activity所有字型,若我們只需要限制某個TextView的最大字型size,而不是全域性,該怎麼辦呢?
第二種方法,自定義TextView以區域性控制字型大小上限:
public class LimitSizeTextView extends TextView {
private float mLimitFontScale = 0; // 若在TextView例項化時沒有呼叫setLimitFontScale則預設值為0
private float mRealTextSize = 0;
public LimitSizeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setLimitFontScale(float limitFontScale) {
this.mLimitFontScale = limitFontScale;
}
@Override
public void setText(CharSequence text, BufferType type) {
if (mLimitFontScale > 0 && !TextUtils.equals(text, getText())) {
// 若設定了最大字型尺寸,則強制改變size,避免系統超大字型等情況導致字型過大
super.setText(text, type);
float curFontScale = getResources().getConfiguration().fontScale;
if (curFontScale >= mLimitFontScale) {
if (mRealTextSize == 0) {
// 字型大小隻修正一次
mRealTextSize = getTextSize() * (mLimitFontScale / curFontScale);
}
// 注意這裡設定大小的單位是畫素
setTextSize(TypedValue.COMPLEX_UNIT_PX, mRealTextSize);
}
} else {
super.setText(text, type);
}
}
}
其實思想和第一種方法類似,都是“劫持”一下系統API,來達到我們的目的。