Android笔记之TypedArray中dimension不同的值

644 阅读2分钟

一 熟悉的TypedArray,头晕的dimension

在我们使用typedarray的时候,会在xml中定义dimension值,这个一般是和长度有关的。但是我们在获取这个值的时候,会发现有三个不同的方法来获取,那么这三个有什么区别呢?

二 dimension三兄弟


可以发现三者的参数都一样,一个是id,一个是默认值。

2.1 老大:getDimension

老大的返回值是float,文档上对他的描述是:返回id对应的尺寸值。详细的描述是

Retrieve a dimensional unit attribute at index. Unit conversions are based on the current DisplayMetrics associated with the resources this TypedArray object came from.
简单的说起来就是基于当前DisplayMetrics转换的尺寸值,在这里就不细讲了,我们主要关注区别。
所以老大就是返回的一个float值

2.2 老二:getDimensionPixelOffset

返回一个int,这其实就是老大和老二最大的差距,但是这个int是什么,我们去看文档。

Retrieve a dimensional unit attribute at index for use as an offset in raw pixels. This is the same as getDimension(int, float), except the returned value is converted to integer pixels for you. An offset conversion involves simply truncating the base value to an integer.

原来就是吧老大返回的float转成了int给你。这里需要注意一下,float强转成int的时候并不是按照小数点后四舍五入的,是直接截断的,就像

float f1 = 2.1f;
float f2 = 2.9f;
//(int) f1 =2, (int)f2 = 2.

2.3 老三:getDimensionPixelSize

老三的返回值也是int,但是和老二有什么区别呢?

Retrieve a dimensional unit attribute at index for use as a size in raw pixels. This is the same as getDimension(int, float), 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.

可以看出来同样是转成int,老三是小数点后四舍五入。
这样明白了三兄弟的区别后,我们就可以根据实际需要来选择了。 //作为Android开发的初学者,如果我有错误的地方或者不足的话欢迎大家指正。希望与大家一同进步。