113

In dimens.xml, I have:

<dimen name="text_medium">18sp</dimen>

In runtime, I get this value and set the text size of a text view:

int size = context.getResources().getDimensionPixelSize(R.dimen.text_medium);
textView.setTextSize(size).

On a 10″ tablet (1280 x 800), everything is ok; but on a phone (800 x 480), the text view has a very large font. On the tablet, the size equals 18; on the phone, it's 27.

If I set the size manually by:

textView.setTextSize(size)

the size is normal on both devices.

4

4 回答 4

317

在dimens.xml添加维度:

   <dimen name="text_medium">18sp</dimen>

在代码中设置大小:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));
于 2013-05-23T15:31:06.197 回答
4

getDimensionPixelSize() 和 getDimension() 两种方法都使用屏幕密度来计算像素。您的手机屏幕密度显然是 hdpi (240dpi),因此它使用 1.5 比例将 dp 转换为 sp。简单数学 18 * 1.5 = 27。

您的平板电脑密度似乎是 mdpi (160dpi),因此比例仅为 1:1。

但是,如果您比较两个文本的实际大小,它应该是相同的。

最好的方法是创建两个 dimens.xml 文件,一个在 values 文件夹中用于手机,另一个在 values-sw600dp 中用于平板电脑(您也可以使用 values-sw720dp-land 文件夹来存储横向方向的 10 英寸平板电脑的尺寸)。

您可以在以下网址阅读更多关于 Android 尺寸的信息:http ://android4beginners.com/2013/07/appendix-c-everything-about-sizes-and-dimensions-in-android/

于 2013-07-06T14:56:00.953 回答
1

您可以使用 sdp(可缩放密度像素)https://github.com/intuit/sdp代替 dp,这肯定会挽救您的生命

于 2017-07-31T11:23:07.470 回答
1

To expand on Kostek Poland's answer,

The reason why your text size doesn't appear as expected is because in this line:

int size = context.getResources().getDimensionPixelSize(R.dimen.text_medium);

getDimensionPixelSize() converts "18sp" to pixel size, so the returned value is a different value than 18. Lets say for example the method returns a value of 23. Therefore when this line is executed:

textView.setTextSize(size)

The method sets your text size to 23sp, so your text size will appear larger than expected.

The Solution is to use this line instead when setting your text size:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));

This works because the first argument states that the second argument is of type pixel. So now if the second argument is 23 then it wont be treated like it is 23sp, but instead means 23 pixels which is equivalent to the 18sp but in pixel units.

于 2021-04-14T05:52:37.423 回答