Android 自定义View onMeasure
// MeasureSpec 源码 删除了注释 public static class 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; public static int makeMeasureSpec(int size, int mode) { return size + mode; } public static int getMode(int measureSpec) { return (measureSpec & MODE_MASK); } public static int getSize(int measureSpec) { return (measureSpec & ~MODE_MASK); } 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(); } }
// MeasureSpec.AT_MOST (wrap_content) 代表的是最大可获得的空间 // MeasureSpec.EXACTLY (fill_parent/match_parent) 代表的是精确的尺寸 // MeasureSpec.UNSPECIFIED 对于控件尺寸来说,没有任何参考意义。 // 指定自定义View的最小宽高 private static int MIN_WIDTH_SIZE = 50; private static int MIN_HEIGHT_SIZE = 50; @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 测量方法 super.onMeasure(widthMeasureSpec, heightMeasureSpec); int width = MeasureSpec.getSize(widthMeasureSpec); int height = MeasureSpec.getSize(heightMeasureSpec); int wmode = MeasureSpec.getMode(widthMeasureSpec); int hmode = MeasureSpec.getMode(heightMeasureSpec); int w = 0, h = 0; w = this.measureSize(wmode, width, MIN_WIDTH_SIZE); h = this.measureSize(hmode, height, MIN_HEIGHT_SIZE); // 设置测量大小 super.setMeasuredDimension(w, h); } // 计算测量大小 public int measureSize(int mode, int measureSize, int minSize) { int size = 0; if (mode == MeasureSpec.AT_MOST) { size = minSize; } else if (mode == MeasureSpec.EXACTLY) { size = measureSize; } else { // UNSPECIFIED size = minSize; } return size; }
PS:关于MeasureSpec的解释来自网上搜索