Android API之android.view.View.MeasureSpec
android.view.View.MeasureSpec
MeasureSpec是View的内部类
public static class MeasureSpec
MeasureSpec封装从parent传递给child的layout要求。每个MeasureSpec表示对width/height的要求。MeasureSpec由size和mode组成。可用的mode有3种:
1. UNSPECIFIED表示parent没有强加给child任何constraint。
2. EXACTLY表示parent已经确定child的精确size。
3. AT_MOST表示child可以设定为specified size之内的任何值。
MeasureSpec实现为int类型,相比object类型,降低了allocation。可以将<size, mode>元组pack和unpack为int类型。
MeasureSpec定义的常量有:
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
public static final int EXACTLY = 1 << MODE_SHIFT;
public static final int AT_MOST = 2 << MODE_SHIFT;
MeasureSpec定义的方法有:
public static String toString(int measureSpec) {
int mode = getMode(measureSpec);
int size = getSize(measureSpec);
StringBuilder sb = new StringBuilder("MeasureSpec: ");
if (mode == UNSPECIFIED)
sb.append("UNSPECIFIED ");
else if (mode == EXACTLY)
sb.append("EXACTLY ");
else if (mode == AT_MOST)
sb.append("AT_MOST ");
else
sb.append(mode).append(" ");
sb.append(size);
return sb.toString();
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
public static int makeMeasureSpec(int size, int mode) {
return size + mode;
}