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

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


当前回答

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

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

</resources>

其他回答

最简单的方法就是使用如下代码:

android:textSize="32sp"

如果你想了解更多关于textSize属性的信息,你可以查看Android开发者文档。

在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

防止整个应用程序受到系统字体大小影响的简单方法是使用一个基本活动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());
}

实际上,设置字体大小只影响sp中的大小。所以你所需要做的-在dp中定义textSize而不是sp,然后设置不会改变应用程序中的文本大小。

这里是文档的链接:Dimensions

但是请注意,预期的行为是所有应用程序中的字体都尊重用户的偏好。用户可能有很多原因想要调整字体大小,其中一些甚至可能是医疗视力受损的用户。使用dp而不是sp作为文本可能会导致不情愿地歧视你的应用程序的一些用户。

即:

android:textSize="32dp"

你可以使用下面的代码:

android:textSize="32dp"

它解决了你的问题,但你必须知道你应该尊重用户的决定。 这样,从设备设置中更改文本大小不会更改此值。这就是用sp代替dp的原因。 所以我的建议是使用不同的系统字体大小(小,正常,大,…)

https://stacklearn.ir