Android事件分发机制源码分析上----View事件分发分析

来源:互联网 发布:英语在线交流软件 编辑:程序博客网 时间:2024/06/06 00:35

        今天给大家带来一篇事件分发机制的分析。

      Android学习的一道门槛是自定义View&ViewGroup,自定义View中相对重要的是自定义属性,然后重写onMeasure、onLayout、onDraw方法,还有就是自定义View事件冲突的解决,到了这里会有好多疑问,为什么会事件冲突,事件冲突如何解决,onTouch和onTouchEvent什么区别,为什么listView加入滑动功能后,数据列表不能再滚动,广告轮播器(viewPage)图片想要点击为什么要用button而不能用imageView,要很好的解决这些问题,就涉及到了Android的事件分发机制,要了解Android的事件分发机制就要查看android的源码。

     android的两大基础控件类型:View和ViewGroup,所有的控件都继承自View,ViewGroup也继承自View但是却有它自己的特性,这里首先分析View的事件分发机制,从一个简单的例子入手进行分析。

View没有子布局的,ViewGroup继承自View,可以有子控件。而事件即MotionEvent,最重要的有3个:

(1)MotionEvent.ACTION_DOWN  按下View,是所有事件的开始

(2)MotionEvent.ACTION_MOVE   滑动事件

(3)MotionEvent.ACTION_UP       与down对应,表示抬起

 

    分析View的事件传递机制从执行View的点击监听和触摸监听事件开始,首先我们需要明确的一点是,无论是点击还是滑动,只要你触摸到了任何一个控件,就一定会调用该控件的dispatchTouchEvent方法,然后才会执行后面的事件过程:

        

    布局文件中添加一个按钮,然后给按钮添加click监听和touch事件,监听,实例代码:

 

public class MainActivity extends AppCompatActivity {    public static final String TAG="MainActivity";    Button button1;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button1= (Button) findViewById(R.id.button1);        button1.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                System.out.println(TAG+"===onClick()");            }        });        button1.setOnTouchListener(new View.OnTouchListener() {            @Override            public boolean onTouch(View v, MotionEvent event) {                System.out.println(TAG+"===onTouch()"+"eventAction"+event.getAction());                return false;            }        });    }}


如果点击button产下下面的结果:

I/System.out( 2147):MainActivity===onTouch()eventAction===0

I/System.out( 2147):MainActivity===onTouch()eventAction===1

I/System.out( 2147): MainActivity===onClick()

 

       可以看到onTouch事件被执行了两次,分别由ACTION_DOWN和ACTION_UP触发,onClick则触发了一次;如果我把鼠标放在按钮上多蹭几下的话,ACTION_MOVE会触发多次的ontouch事件。还有一个明显的结果是每次都是率先执行onTouch之后才执行onClick事件,我们可以先得出一个结论onTouch事件先于onClick事件被调用。这些事件都是被dispatchTouchEvent()函数分发给自身事件后才能被处理。

   下面开始进入view源码里,这里举例利用的Button,可以看到button的源码,Button继承自TextView,TextView又继承自View,我们要找的分发事件的dispatchTouchEvent不在Button也不再TextView中,而是在View源码中。
public class Button extends TextView
public class TextView extends View
到了此处还没有出现,onTouchEvent事件和dispatchTouchEvent,下面我们将通过继承Button的方式,查看带有onTouchEvent和DispatchTouchEvent事件的事件执行过程。
自定义控件,继承自Button,重写onTouchEvent&dispatchTouchEvent代码实例:
 
/** * Created by user on 17-3-26. */public class MyButton extends Button {    public static final String TAG = "MyButton";    public MyButton(Context context) {        super(context);    }    public MyButton(Context context, AttributeSet attrs) {        super(context, attrs);    }    public MyButton(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);    }    @Override    public boolean dispatchTouchEvent(MotionEvent event) {        System.out.println(TAG + "====dispatchTouchEvent");          return super.dispatchTouchEvent(event);        //return false;    }    @Override    public boolean onTouchEvent(MotionEvent event) {        System.out.println(TAG + "====onTouchEvent");        return super.onTouchEvent(event);        //return false;    }}


点击按钮后的执行顺序:
I/System.out(27995): MyButton====dispatchTouchEvent
I/System.out(27995): MainActivity===onTouch()eventAction===0
I/System.out(27995): MyButton====onTouchEvent
I/System.out(27995): MyButton====dispatchTouchEvent
I/System.out(27995): MainActivity===onTouch()eventAction===1
I/System.out(27995): MyButton====onTouchEvent
I/System.out(27995): MainActivity===onClick()
 

        点击Button按钮事件分发过程如下 ,如果我们在onTouchEvent事件中区分Motion_UP和Motion_Down事件,就可以知道onClick方法发生在Motion_UP事件之后。dispatchTouchEvent---->onTouch---->onTouchEvent----->onClick

下面我们从dispatchTouchEvent函数开始分析,因为它首先被调用,
DispatchTouchEvent的源码如下:
public boolean dispatchTouchEvent(MotionEvent event) {    // If the event should be handled by accessibility focus first.    if (event.isTargetAccessibilityFocus()) {        // We don't have focus or no virtual descendant has it, do not handle the event.        if (!isAccessibilityFocusedViewOrHost()) {            return false;        }        // We have focus and got the event, then use normal event dispatch.        event.setTargetAccessibilityFocus(false);    }    boolean result = false;    if (mInputEventConsistencyVerifier != null) {        mInputEventConsistencyVerifier.onTouchEvent(event, 0);    }    final int actionMasked = event.getActionMasked();    if (actionMasked == MotionEvent.ACTION_DOWN) {        // Defensive cleanup for new gesture        stopNestedScroll();    }    if (onFilterTouchEventForSecurity(event)) {        if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {            result = true;        }        //noinspection SimplifiableIfStatement        ListenerInfo li = mListenerInfo;        if (li != null && li.mOnTouchListener != null                && (mViewFlags & ENABLED_MASK) == ENABLED                && li.mOnTouchListener.onTouch(this, event)) {            result = true;        }        if (!result && onTouchEvent(event)) {            result = true;        }    }    if (!result && mInputEventConsistencyVerifier != null) {        mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);    }    // Clean up after nested scrolls if this is the end of a gesture;    // also cancel it if we tried an ACTION_DOWN but we didn't want the rest    // of the gesture.    if (actionMasked == MotionEvent.ACTION_UP ||            actionMasked == MotionEvent.ACTION_CANCEL ||            (actionMasked == MotionEvent.ACTION_DOWN && !result)) {        stopNestedScroll();    }    return result;}


代码较多,这里我们只看关键代码:
ListenerInfo li = mListenerInfo;if (li != null && li.mOnTouchListener != null        && (mViewFlags & ENABLED_MASK) == ENABLED        && li.mOnTouchListener.onTouch(this, event)) {    result = true;}if (!result && onTouchEvent(event)) {    result = true;}


重点分析:

       onTouch事件和onTouchEvent事件都是有返回值的,而onClick事件没有返回值。首先是进行了一个判断,如果mOnTouchListener != null,(mViewFlags &ENABLED_MASK) == ENABLED和mOnTouchListener.onTouch(this,event)这三个条件都为真,就返回true,否则就去执行onTouchEvent(event)方法并返回。

(1) 第一个条件判断mOnTouchListener !=null,可以在源码中找到对mOnTouchListener 的赋值操作:
 
public void setOnTouchListener(OnTouchListener l) {        getListenerInfo().mOnTouchListener = l;}

      mOnTouchListener赋值的操作发生在setOnTouchListener方法,当我们给控件添加touch事件,mOnTouchListener就一定被赋值了,也就不再等于空,此条件成立。

(2) 再看第二个条件(mViewFlags & ENABLED_MASK) == ENABLED是判断当前点击的控件是否是enable的,android中很多控件不可点击,但是Button默认都是enable的,因此这个条件恒定为true。

(3)最后看第三个条件,mOnTouchListener.onTouch(this, event),意思很明确就是要根据调控件注册touch事件时的onTouch方法的返回值判断。如果我们在onTouch方法里返回true,第三个条件就为true,从而整个方法直接返回true。如果我们在onTouch方法里返回false,就会走到下面的onTouchEvent(event)方法中,去执行onTouchEvent方法。

         上面的实验中onClick方法被最后执行,但是我们并没有在源码中看到onClick方法的执行,所以很有可能onClick方法是在onTouchEvent方法内部的,进入onTouchEvent方法中,方法比较长只分析重点部分,onClick方法发生在Motion_UP事件之后,所以从Motion_UP进行分析:

case MotionEvent.ACTION_UP:    boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;    if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {        // take focus if we don't have it already and we should in        // touch mode.        boolean focusTaken = false;        if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {            focusTaken = requestFocus();        }        if (prepressed) {            // The button is being released before we actually            // showed it as pressed.  Make it show the pressed            // state now (before scheduling the click) to ensure            // the user sees it.            setPressed(true, x, y);       }        if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {            // This is a tap, so remove the longpress check            removeLongPressCallback();            // Only perform take click actions if we were in the pressed state            if (!focusTaken) {                // Use a Runnable and post this rather than calling                // performClick directly. This lets other visual state                // of the view update before click actions start.                if (mPerformClick == null) {                    mPerformClick = new PerformClick();                }                if (!post(mPerformClick)) {                    performClick();                }            }        }


内部调用了PerformClick(),它的内部调用了onClick()事件;
public boolean performClick() {    final boolean result;    final ListenerInfo li = mListenerInfo;    if (li != null && li.mOnClickListener != null) {        playSoundEffect(SoundEffectConstants.CLICK);        li.mOnClickListener.onClick(this);//调用了onClick事件        result = true;    } else {        result = false;    }    sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);    return result;}


         分析完了这三个条件和onClick事件的执行,我们就可以解释很多事件冲突的问题,总的来说触摸控件会首先调用控件的dispatchTouchEvent,dispatchTouchEvent中最先执行的是onTouch方法,如果在onTouch方法里返回了true,就会让dispatchTouchEvent方法直接返回true,不会再继续往下执行。否则事件会继续传递,执行onTouchEvent函数,在其内部执行onClick事件,如果重写了onTouchEvent事件,执行逻辑后直接返回false或者true,则onClick事件也不会被执行,只有返回super.onTouchEvent(event),才会执行调用onclick的逻辑。

 

onTouch事件的分析

      上面已经对View的事件分发进行了完整的分析,我们也已经了解了其全部过程,但View的onTouch事件还没有深入分析,如果设置了onTouchListener,onTouchEvent事件会在DispatchTouchEvent执行后就开始执行,每次点击它的时候都会触发一系列的ACTION_DOWN,ACTION_MOVE,ACTION_UP等事件。根据上面得出的结论可以知道,但执行ACTION_DOWN事件时如果我们返回一个true,则后面的事件不会再执行,因为三个条件中第三个不满足。

代码修改如下:

 

button1.setOnTouchListener(new View.OnTouchListener() {    @Override    public boolean onTouch(View v, MotionEvent event) {        System.out.println(TAG+"===onTouch()"+"eventAction"+"==="+event.getAction());        switch (event.getAction()) {            case MotionEvent.ACTION_DOWN:                System.out.println(TAG+"onTouch====MyButton=====ACTION_DOWN");                break;            case MotionEvent.ACTION_MOVE:                System.out.println(TAG+"onTouch====MyButton=====ACTION_MOVE");                break;            case MotionEvent.ACTION_UP:                System.out.println(TAG+"onTouch====MyButton=====ACTION_UP");                break;        }        return false;    }});


实验的结果:
I/System.out(27995): MyButton====dispatchTouchEvent
I/System.out(27995): MainActivity===onTouch()eventAction===0
I/System.out(27995): MainActivityonTouch====MyButton=====ACTION_DOWN
I/System.out(27995): MyButton====onTouchEvent
I/System.out(27995): MyButton====dispatchTouchEvent
I/System.out(27995): MainActivity===onTouch()eventAction===1
I/System.out(27995): MainActivityonTouch====MyButton=====ACTION_UP
I/System.out(27995): MyButton====onTouchEvent
I/System.out(27995): MainActivity===onClick()
实验结果却出乎我们的意料,ACTION_UP事件依然被执行了,难道前面的总结错了,去翻源代码,我们在onTouch事件中返回了false,则一定会进入到onTouchEvent事件中。
if (li != null && li.mOnTouchListener != null        && (mViewFlags & ENABLED_MASK) == ENABLED        && li.mOnTouchListener.onTouch(this, event)) {    result = true;}if (!result && onTouchEvent(event)) {    result = true;}进入onTouchEvent()://由于按钮总可以被点击,则if条件一定为true,则会进入switch(),最终一定会返回true; if (((viewFlags & CLICKABLE) == CLICKABLE ||                (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||                (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {            switch (action) {                case MotionEvent.ACTION_UP:                 case MotionEvent.ACTION_DOWN:                    break;            }             return true;        }


       所以最终,onTouchEvent还是会返回true,ACTION_UP也会被执行。说到这里,如果我们换成不能被点击的控件,如果ACTION_DOWN时返回false,则后面的up事件就不会被执行了。

 

总结:View的事件分发,只要理解源码的逻辑就可以方便的处理各种事件冲突,下面对View的事件分发机制做个总结。

触摸控件会首先调用控件的dispatchTouchEvent,而且一定会被调用,onTouch事件和onTouchEvent事件在dispatchTouchEvent的内部,dispatchTouchEvent中最先经过的是onTouch方法,如果满足三个条件(前文总结)就会执行onTouch事件,如果在onTouch方法里返回了true,就会让dispatchTouchEvent方法直接返回true,不会再继续往下执行。这里有一点需要注意,onTouch事件的执行会同时触发ACTION_DOWN和ACTION_UP等事件,对于能被点击的控件,无论执行ACTION_DOWN时返回true或者false对会继续执行ACTION_UP等事件,对于不可点击的控件,如果ACTION_DOWN时返回false,则后面的事件不会再被执行。

    onTouch事件没有返回true,事件会继续传递,执行onTouchEvent函数,在其内部执行onClick事件,如果重写了onTouchEvent事件,执行逻辑后直接返回false或者true,则onClick事件也不会被执行,只有返回super.onTouchEvent(event),才会执行调用onclick的逻辑。下一篇文档会介绍ViewGrou的事件分发机制。完!

0 0
原创粉丝点击