Android中的getDimension,getDimensionPixelOffset和getDimensionPixelSize

疑惑了好久的问题,今天又遇到了。

由于没心情去读英语,所以尝试网上搜了一下,结果发现两种不同的说法:

http://blog.csdn.net/xiahao86/article/details/16823553

http://www.eoeandroid.com/thread-322627-1-1.html

一个是说getDimensionPixelSize对px是否乘以密度的问题,一个是说算出float进位的问题

所以打算自己验证一下

屏幕800x480,密度1.5

15dp 15sp 15px

结果如下:

15dp:  getDimension=22.5    getDimensionPixelOffset=22  getDimensionPixelSize=23

15sp:  getDimension=22.5    getDimensionPixelOffset=22  getDimensionPixelSize=23

15px:  getDimension=15.0   getDimensionPixelOffset=15 getDimensionPixelSize=15

可以看出getDimensionPixelSize还是能识别传入的是dp还是px的,

区别主要是结果进位的问题:

getDimensionPixelOffset是截断

getDimensionPixelSize是四舍五入



附:sdk原文

getDimension:

float android.content.res.Resources.getDimension(int id) throws NotFoundException


Retrieve a dimensional for a particular resource ID. Unit conversions are based on the current DisplayMetrics associated with the resources.

Parameters:
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
Returns:
Resource dimension value multiplied by the appropriate metric.
Throws:
NotFoundException - Throws NotFoundException if the given ID does not exist.



getDimensionPixelOffset:

int android.content.res.Resources.getDimensionPixelOffset(int id) throws NotFoundException


Retrieve a dimensional for a particular resource ID for use as an offset in raw pixels. This is the same as getDimension, except the returned value is converted to integer pixels for you. An offset conversion involves simply truncating the base value to an integer.

Parameters:
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
Returns:
Resource dimension value multiplied by the appropriate metric and truncated to integer pixels.
Throws:
NotFoundException - Throws NotFoundException if the given ID does not exist.
getDimensionPixelSize:

 int android.content.res.Resources.getDimensionPixelSize(int id) throws NotFoundException


Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension, except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Parameters:
id The desired resource identifier, as generated by the aapt tool. This integer encodes the package, type, and resource entry. The value 0 is an invalid identifier.
Returns:
Resource dimension value multiplied by the appropriate metric and truncated to integer pixels.
Throws:
NotFoundException - Throws NotFoundException if the given ID does not exist.

这里有提到getDimensionPixelSize会至少保留1像素,这个要注意一下


你可能感兴趣的:(Android)