官方文档似乎没有回答这个问题,或者我可以想不通.
The official documentation does not seem to answer this, or I can't figure it out.
元素(别管 AlertDialog
,它也发生在任何 TextView 上):
Element (nevermind the AlertDialog
, it happens on any TextView as well):
TextView tv = (TextView) dialog.findViewById(android.R.id.message);
不一致.案例A:
tv.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
// or tv.setTextSize(14); does the same
案例 B:
tv.setTextSize(getResources().getDimension(R.dimen.text_size_small));
// TypedValue makes no difference either.
values/dimens.xml
在哪里:
<dimen name="text_size_small">14sp</dimen>
结果:字体大小不一样,从资源中检索时显得更大.我可能遗漏了一些东西,所以我的错误是什么,最重要的是:为什么?
Result: font size is not the same, and appears much bigger when retrieving from resource. I'm probably missing something, so what's my mistake, and the most important: why?
-- 更新到第一个答案--
固定数字只是一个例子,因为没有人会在代码中硬编码固定字体大小.所以让我重新表述这个问题:
The fixed number was just an example, as nobody would hard code fixed font sizes in code. So let me rephrase the question:
为什么如果我从代码中获取资源,文本大小比我从 XML 布局中获取资源时大? 此外,问题仍然相同:如何检索 14sp代码中的单元并使其与布局 XML 中设置的 14sp 单元保持一致?我没有接受答案,因为它没有告诉我如何在代码中使用资源中的 sp 单位来获取文本大小.
Why if I get the resource from code, the text size is bigger than when I get the resource from a XML layout? Besides, the question is still the same: how do I retrieve a 14sp unit in code and keep it consistent with the 14sp unit that is set in the layout XML? I did not accept the answer because it does not tell me how to use sp units from resource in code for text size.
在这种布局上,字体大小不同,即使尺寸相同:
On this layout, the font size is different, even if the dimension is the same:
<TextView
android:id="@+id/my_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/TextBody" />
styles.xml:
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>
看到 text_size_small 了吗?为什么在这种情况下字体大小比代码中的小,使用相同的 dimen
资源?
See text_size_small there? Why in this case the font size is smaller than in the code, using the same dimen
resource?
你应该使用 setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
因为 getDimension
方法的文档声明它返回一个 Resource 维度值乘以适当的指标.
我理解为预先计算的绝对 px 值.
You should use setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
because the documentation of the getDimension
method states that it returns a Resource dimension value multiplied by the appropriate metric.
which I understand to be the precalculated absolute px value.
即使用:
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_size_small));
这篇关于在代码和资源中设置 TextView 字体大小时不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!