我想在我的应用程序中指定我自己的文本大小,但我这样做有一个问题。

当我在设备设置中改变字体大小时,我的应用程序TextView的字体大小也会改变。


当前回答

在android 8中,这个解决方案适合我

在基本活动中添加此代码

@Override
protected void attachBaseContext(Context newBase) {
    super.attachBaseContext(newBase);
    final Configuration override = new Configuration(newBase.getResources().getConfiguration());
    override.fontScale = 1.0f;
    applyOverrideConfiguration(override);
}

源 https://stackoverflow.com/a/57225687/7985871

其他回答

我通常在资源文件中改变大小

<resources>
    <dimen name="siez_1">40px</dimen>
    <dimen name="siez_2">50px</dimen>
    <dimen name="siez_3">60px</dimen>

</resources>

这可能会有所帮助。将代码添加到您的自定义Application或BaseActivity中

/**
 * 重写 getResource 方法,防止系统字体影响
 *
 * @return
 */
@Override
public Resources getResources() {
    Resources resources = super.getResources();
    if (resources != null && resources.getConfiguration().fontScale != 1) {
        Configuration configuration = resources.getConfiguration();
        configuration.fontScale = 1;
        resources.updateConfiguration(configuration, resources.getDisplayMetrics());
    }
    return resources;
}

然而,Resource#updateConfiguration是在API级别25中部署的,这意味着在未来的某一天它将不受支持。

如果已经在dimension .xml文件中定义了DIP或SP,那么必须通过代码再次指定DIP或SP并不是一件好事。

我认为最好的选择是在使用dimension .xml值时使用PX:

tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.txt_size));

这样,如果需要,您可以在dimension .xml文件中从DP切换到SP,而无需更改任何代码。

在Activity中重写getResources()。

设置TextView的大小在sp通常像android:textSize="32sp"

override fun getResources(): Resources {
    return super.getResources().apply {
        configuration.fontScale = 1F
        updateConfiguration(configuration, displayMetrics)
    }
}

还要注意,如果在代码中设置了textSize,调用textView.setTextSize(X)将数字(X)解释为SP。COMPLEX_UNIT_DIP, X)在dp中设置值。