在代码和资源中设置TextView字体大小时不一致

dav*_*ino 62 android dialog dimension text-size

官方文档似乎并没有回答这个问题,或者我不明白.

元素(没关系AlertDialog,它也发生在任何TextView上):

TextView tv = (TextView) dialog.findViewById(android.R.id.message);
Run Code Online (Sandbox Code Playgroud)

不一致性.案例A:

tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
// or tv.setTextSize(14); does the same
Run Code Online (Sandbox Code Playgroud)

案例B:

tv.setTextSize(getResources().getDimension(R.dimen.text_size_small));
// TypedValue makes no difference either.
Run Code Online (Sandbox Code Playgroud)

values/dimens.xml它在哪里:

<dimen name="text_size_small">14sp</dimen>
Run Code Online (Sandbox Code Playgroud)

结果:字体大小不一样,从资源检索时显得更大.我可能错过了什么,所以我的错误是什么,最重要的是:为什么?

- 更新到第一个答案 -

固定数字只是一个例子,因为没有人会在代码中硬编码固定的字体大小.那么让我重新解释一下这个问题:

为什么如果从代码中获取资源,文本大小比从XML布局获取资源时要大?此外,问题仍然是相同的:如何在代码中检索14sp单元并使其与布局XML中设置的14sp单元保持一致?我没有接受答案,因为它没有告诉我如何在代码中使用资源中的sp单位来处理文本大小.

在此布局上,即使尺寸相同,字体大小也不同:

<TextView
            android:id="@+id/my_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="@style/TextBody" />
Run Code Online (Sandbox Code Playgroud)

styles.xml:

<style name="TextBody">
    <item name="android:textSize">@dimen/text_size_small</item>
    <item name="android:lineSpacingMultiplier">1.1</item>
    <item name="android:textColor">@color/body_text_1</item>
    <item name="android:textIsSelectable">true</item>
    <item name="android:linksClickable">true</item>
</style>
Run Code Online (Sandbox Code Playgroud)

看到text_size_small吗?为什么在这种情况下字体大小比使用相同dimen资源的代码小?

max*_*xmc 103

你应该使用,setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);因为该getDimension方法的文档声明它返回一个Resource dimension value multiplied by the appropriate metric.我理解为预先计算的绝对px值.

也就是说,使用:

tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size_small));
Run Code Online (Sandbox Code Playgroud)


DaR*_*lla 24

不知何故,这似乎适合:

XML:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="typo14">9sp</dimen>
</resources>
Run Code Online (Sandbox Code Playgroud)

Java的:

setTextSize(TypedValue.COMPLEX_UNIT_SP, 9);
setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.typo14));
Run Code Online (Sandbox Code Playgroud)