View的三种模式
-
EXACTLY:精确模式,当输入准确的数字时适配此模式
-
AT_MOST:最大模式,适配wrap_content
-
UNSPECIFIED:不指定模式(不知道干嘛的)
当我们重写onMeasure()方法时,系统回调super.onMeasure();方法中,底层通过setMeasureDimension()方法实现View的侧量
模板代码如下
public class MyView extends View { public MyView(Context context) { super(context); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension( measureWidth(widthMeasureSpec), measureHeight(heightMeasureSpec) ); } /** * 获得实际宽度 * @param widthMeasureSpec 带模式和值的宽度spec对象 * @return 实际测量值 */ private int measureWidth(int widthMeasureSpec) { int result = 0; int spaceMode = MeasureSpec.getMode(widthMeasureSpec); int spaceSize = MeasureSpec.getSize(widthMeasureSpec); if (spaceMode == MeasureSpec.EXACTLY){ result = spaceSize; }else{ result = 200;//设置宽度默认值 if (spaceMode == MeasureSpec.AT_MOST){ result = Math.min(result,spaceSize); } } return result; } /** * 获得实际宽度 * @param heightMeasureSpec 带模式和值的高度spec对象 * @return 实际测量值 */ private int measureHeight(int heightMeasureSpec) { int result = 0; int specMode = MeasureSpec.getMode(heightMeasureSpec); int specSize = MeasureSpec.getSize(heightMeasureSpec); if (specMode == MeasureSpec.EXACTLY){ result = specSize; }else { result = 200;//设置高度默认值 if (specMode == MeasureSpec.AT_MOST){ result = Math.min(result,specSize); } } return result; } }