问题描述
借助官方文档似乎没有回答这个问题,或者我可以T看着办吧。
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:
Inconsistency. Case 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.
其中,值/ 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?
- 更新到第一个答案 -
固定号码只是一个例子,因为没有人会辛苦code固定的字体大小在code。因此,让我改一下这个问题:
The fixed number was just an example, as nobody would hard code fixed font sizes in code. So let me rephrase the question:
为什么,如果我得到code中的资源,文本大小大于当我从一个XML布局资源此外,问题还是一样:?我该怎么办在code检索14sp单元和保持与在布局XML设置14sp单位保持一致?我没有接受的答案,因为它并没有告诉我如何在code使用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呢?为什么在这种情况下,字体大小比在code较小,使用相同的扪
资源?
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
法说,它返回一个资源维度值乘以相应的指标。
我的理解是precalculated绝对像素值。
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的字体大小code和资源不一致时,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!