MeasureSpec封装了从父容器传递给子容器的布局需求.
每一个MeasureSpec代表了一个宽度,或者高度的说明.
一个MeasureSpec是一个大小跟模式的组合值.一共有三种模式.
A MeasureSpec encapsulates the layout requirements passed fromparent to child Each MeasureSpec represents a requirement foreither the width or the height.A MeasureSpec is compsized of a sizeand a mode.There are three possible modes:
(1)UPSPECIFIED :父容器对于子容器没有任何限制,子容器想要多大就多大.
UNSPECIFIED The parent has not imposed any constraint on thechild.It can be whatever size it wants
(2) EXACTLY
父容器已经为子容器设置了尺寸,子容器应当服从这些边界,不论子容器想要多大的空间.
EXACTLY The parent has determined and exact size for the child.Thechild is going to be given those bounds regardless of how big itwants to be.
(3) AT_MOST
子容器可以是声明大小内的任意大小.
AT_MOST The child can be as large as it wants up to the specifiedsize
MeasureSpec是View类下的静态公开类,MeasureSpec中的值作为一个整型是为了减少对象的分配开支.此类用于
将size和mode打包或者解包为一个整型.
MeasureSpecs are implemented as ints to reduce objectallocation.This class is provided to pack and unpack the size,modetuple into the int
我比较好奇的是怎么样将两个值打包到一个int中,又如何解包.
MeasureSpec类代码如下 :(注释已经被我删除了,因为在上面说明了.)
01 | public static class MeasureSpec{ |
02 |
private static final int MODE_SHIFT= 30 ; |
03 |
private static final int MODE_MASK= 0x3 <<MODE_SHIFT; |
04 |
05 |
public static final int UNSPECIFIED= 0 <<MODE_SHIFT; |
06 |
public static final int EXACTLY= 1 <<MODE_SHIFT; |
07 |
public static final int AT_MOST= 2 <<MODE_SHIFT; |
08 |
09 |
public static int makeMeasureSpec( int size, int mode){ | 【】
10 |
return size+ mode; |
11 |
} |
12 |
public static int getMode( int measureSpec){ |
13 |
return (measureSpec& MODE_MASK); |
14 |
} |
15 |
public static int getSize( int measureSpec){ |
16 |
return (measureSpec& ~MODE_MASK); |
17 |
}} |
我无聊的将他们的十进制值打印出来了:
mode_shift=30,mode_mask=-1073741824,UNSPECIFIED=0,EXACTLY=1073741824,AT_MOST=-2147483648
然后觉得也应该将他们的二进制值打印出来,如下:
mode_shift=11110, // 30
mode_mask=11000000000000000000000000000000,
UNSPECIFIED=0,
EXACTLY=1000000000000000000000000000000,
AT_MOST=10000000000000000000000000000000
1 | MODE_MASK= 0x3 <<MODE_SHIFT //也就是说MODE_MASK是由11左移30位得到的.因为Java用补码表示数值.最后得到的值最高位是1所以就是负数了 |
1 |
而把MODE_SHIFF就看成30.那为什么是二进制 的11呢?
呢,因为只有三各模式,如果有四种模式就是111了因为111三个位才可以有四种组合对吧.
我们这样来看,
UNSPECIFIED=00000000000000000000000000000000,
EXACTLY=01000000000000000000000000000000,
AT_MOST=10000000000000000000000000000000
也就是说,0,1,2
对应 00,01,10
当跟11想与时 00 &11 还是得到00,11&01 ->01,10&
我觉得到了这个份上相信,看我博客的也都理解了.
return (measureSpec &~MODE_MASK);应该是return (measureSpec& (~MODE_MASK));