問題描述
官方文檔似乎沒有回答這個問題,或者我可以想不通.
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 字體大小時不一致的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!