1、重写onMeasure()方法的目的:
-
重写onMeasure()方法的目的就是为了设置Wrap_content的情况下View的宽和高的值。
-
因为在View类的oMeasure()方法中的getDefaultSize()方法中MeasureSpec为EXACTLY和AT_MOST两种情况返回的size都为specSize(MeasureSpec.getSize(measureSpec))
-
而specSize即为父布局所剩余的size
-
specSize又是ViewGroup通过measureChildWithMargin()方法中的getChildMeasureSpec()中计算出来封存到MeasureSpec中的
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec , heightMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpceSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode=MeasureSpec.getMode(heightMeasureSpec);
int heightSpceSize=MeasureSpec.getSize(heightMeasureSpec);
if(widthSpecMode==MeasureSpec.AT_MOST&&heightSpecMode==Mea sureSpec.AT_MOST){
setMeasuredDimension(mWidth, mHeight);
}else if(widthSpecMode==MeasureSpec.AT_MOST){
setMeasuredDimension(mWidth, heightSpceSize);
}else if(heightSpecMode==MeasureSpec.AT_MOST){
setMeasuredDimension(widthSpceSize, mHeight);
}
}
2、invalidate()和postInvalidate()
- invalidate() 主线程中调用
- postInvalidate()子线程中调用,内部实现是handler发送延迟消息,最终还是调用了invalidate()
3、事件分发机制
其实事件分发机制,可以分为两个过程,一个是向下分发过程,一个是向上返回过程,其中向下分发是靠dispatchTouchEvent 方法,从Activity的dispatchTouchEvent 直到目标视图的dispatchTouchEvent ,然后进入目标视图的onTouchEvent,向上返回则是靠onTouchEvent,从目标视图的onTouchEvent直到Activity的onTouchEvent。
而在向下分发的过程可能会提前结束,这受onInterceptTouchEvent影响,也可能是ViewGroup没有子视图了,在两个因素都可以使该过程提前结束,从而提前进入向上返回的过程。向上返回过程也可能提前结束,如果事件在onTouchEvent中返回true,即事件被消费,那么事件不会继续向上传递,该过程提前结束。
参考: Android事件分发机制
网友评论