【问题标题】:TypedValue.applyDimension producing wrong dimensionsTypedValue.applyDimension 产生错误的尺寸
【发布时间】:2020-06-07 11:24:25
【问题描述】:

我使用 TypedValue.applyDimension 和 displayMetrix.scaledDensity 在我的小米 Redmi 5 plus 上的 TextView 中设置文本大小并获得令人惊讶的结果:TextView 中的文本远大于布局属性中设置的文本(相同的 sp 值)。这是我的布局:

<TextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center|start"
    android:layout_margin="4dp"
    android:text="Some Text"
    android:textSize="18sp" />

这是我如何更改文本大小:

TextView titleView = itemView.findViewById(R.id.my_text_view);
titleView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 18, 
        getResources().getDisplayMetrics()));

我也尝试使用如下公式:

(int) getResources().getDisplayMetrics().scaledDensity * 18

在模拟器上,我得到了正确的文本大小,所以我不确定如何重现它。如果有人设法做到这一点,请留下 cmets 让我和其他人了解实际出了什么问题。 谢谢

【问题讨论】:

  • 在手机设置中检查手机的fintsize是否很大。这可能会增加文本视图中文本的大小。
  • @NIKHIL 在设置中很小。另外,如果我在 XML 布局中设置大小,它会正确显示

标签: android android-layout textview text-size android-screen


【解决方案1】:

所以,我打开TextView source code,发现 TextView.setTextSize 接受 sp,而不是 px。所以答案不是将sp转为px,而是默认使用sp,或者,如果需要支持多个尺寸单位,使用setTextSize(int unit, float size)

【讨论】:

    猜你喜欢
    • 2018-12-31
    • 2021-09-28
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-01
    相关资源
    最近更新 更多