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

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


当前回答

如果已经在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,而无需更改任何代码。

其他回答

如果使用的单位是SP,而不是DP,并且你想覆盖系统字体缩放,你所要做的就是覆盖activity中的一个方法——请看这篇文章。

资源。updateConfiguration已弃用且有bug(在Oreo上,我有格式化文本的问题)。

在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>

将DP更改为sp,这是android的良好实践 android: textSize = " 18 sp "

防止整个应用程序受到系统字体大小影响的简单方法是使用一个基本活动updateConfiguration。

//in base activity add this code.
public  void adjustFontScale( Configuration configuration) {

    configuration.fontScale = (float) 1.0;
    DisplayMetrics metrics = getResources().getDisplayMetrics();
    WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    wm.getDefaultDisplay().getMetrics(metrics);
    metrics.scaledDensity = configuration.fontScale * metrics.density;
    getBaseContext().getResources().updateConfiguration(configuration, metrics);

}

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    adjustFontScale( getResources().getConfiguration());
}