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

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


当前回答

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

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

其他回答

对于kotlin,这对我来说是有效的

priceTextView.textSize = 12f

在Activity中重写getResources()。

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

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

在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

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

像使用字符串资源(DOCS)一样使用资源的维度类型。

在你的dimension .xml文件中,声明你的维度变量:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <dimen name="textview_height">25dp</dimen>
  <dimen name="textview_width">150dp</dimen>
  <dimen name="ball_radius">30dp</dimen>
  <dimen name="font_size">16sp</dimen>
</resources>

然后你可以像这样使用这些值:

<TextView
   android:layout_height="@dimen/textview_height"
   android:layout_width="@dimen/textview_width"
   android:textSize="@dimen/font_size"/>

您可以为不同类型的屏幕声明不同的dimension .xml文件。 这样做可以确保你的应用在不同设备上呈现出理想的外观。

当你不指定android:textSize时,系统使用默认值。