自定义控件

2017-02-15  本文已影响0人  岛在深海处
1、重写onMeasure()方法的目的:
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()
3、事件分发机制

其实事件分发机制,可以分为两个过程,一个是向下分发过程,一个是向上返回过程,其中向下分发是靠dispatchTouchEvent 方法,从Activity的dispatchTouchEvent 直到目标视图的dispatchTouchEvent ,然后进入目标视图的onTouchEvent,向上返回则是靠onTouchEvent,从目标视图的onTouchEvent直到Activity的onTouchEvent。

而在向下分发的过程可能会提前结束,这受onInterceptTouchEvent影响,也可能是ViewGroup没有子视图了,在两个因素都可以使该过程提前结束,从而提前进入向上返回的过程。向上返回过程也可能提前结束,如果事件在onTouchEvent中返回true,即事件被消费,那么事件不会继续向上传递,该过程提前结束。

参考: Android事件分发机制

上一篇 下一篇

猜你喜欢

热点阅读