谈谈对Android View事件分发机制的理解
最近因为项目中用到类似一个linearlayout中水平布局中,有一个textview和button,然后对该linearlayout布局设置点击事件,点击textview能够触发该点击事件,然而奇怪的是点击button却不能触发。然后google到了解决办法(重写button,然后重写其中的ontouchevent方法,且返回值为false),但是不知道原因,这两天看了几位大神的博客,然后自己总结下。
public class mybutton extends button { private final static string tag = "mybutton::zjt"; public mybutton(context context, attributeset attrs) { super(context, attrs); // todo auto-generated constructor stub } public mybutton(context context, attributeset attrs, int defstyle) { super(context, attrs, defstyle); // todo auto-generated constructor stub } @override public boolean ontouchevent(motionevent event) { // todo auto-generated method stub switch (event.getaction()) { case motionevent.action_down: log.e(tag, "ontouchevent action_down"); break; case motionevent.action_move: log.e(tag, "ontouchevent action_move"); break; case motionevent.action_up: log.e(tag, "ontouchevent action_up"); break; default: break; } //return super.ontouchevent(event); return false; } @override public boolean dispatchtouchevent(motionevent event) { // todo auto-generated method stub switch (event.getaction()) { case motionevent.action_down: log.e(tag, "dispatchtouchevent action_down"); break; case motionevent.action_move: log.e(tag, "dispatchtouchevent action_move"); break; case motionevent.action_up: log.e(tag, "dispatchtouchevent action_up"); break; default: break; } return super.dispatchtouchevent(event); } }
mytextview.java
public class mytextview extends textview { private final static string tag = "mytextview : "; public mytextview(context context, attributeset attrs) { super(context, attrs); // todo auto-generated constructor stub } @override public boolean dispatchtouchevent(motionevent event) { // todo auto-generated method stub switch (event.getaction()) { case motionevent.action_down: log.e(tag, "dispatchtouchevent action_down"); break; case motionevent.action_move: log.e(tag, "dispatchtouchevent action_move"); break; case motionevent.action_up: log.e(tag, "dispatchtouchevent action_up"); break; default: break; } return super.dispatchtouchevent(event); } @override public boolean ontouchevent(motionevent event) { // todo auto-generated method stub switch (event.getaction()) { case motionevent.action_down: log.e(tag, "ontouchevent action_down"); ////return true 后面的action_move、和action_up能够得以执行,如果不做任何操作,即 break,由于textview默认是不可点击和长点击的,所以return false, //那么 dispatctouchevent 会 return false,导致后面的action_move 和 action_up不能执行 //return true; break; case motionevent.action_move: log.e(tag, "ontouchevent action_move"); break; case motionevent.action_up: log.e(tag, "ontouchevent action_up"); break; default: break; } return super.ontouchevent(event); } }
mainactivity如下:
public class testtouchactivity extends activity { private final static string tag = "testtouchactivity"; private button mbutton; private textview mtextview; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.my_button_layout); mbutton = (button) findviewbyid(r.id.my_btn); mtextview = (textview) findviewbyid(r.id.my_textview); // mtextview.setonclicklistener(new onclicklistener() { // // @override // public void onclick(view v) { // // todo auto-generated method stub // log.e(tag, "mtextview onclick"); // } // }); mbutton.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub int action = event.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "ontouch action_down"); return true; //break; case motionevent.action_move: log.e(tag, "ontouch action_move"); break; case motionevent.action_up: log.e(tag, "ontouch action_up"); break; default: break; } return false; } }); mtextview.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub int action = event.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "mtextview ontouch action_down"); break; case motionevent.action_move: log.e(tag, "mtextview ontouch action_move"); break; case motionevent.action_up: log.e(tag, "mtextview ontouch action_up"); break; default: break; } return false; } }); } }
点击button和textview的节目如下:
点击textview:
为什么结果是这样的,参考博文已经写得很精彩了,我就站在巨人的肩膀上,总结下,我们从上面的结果可以看出,当我们点击屏幕上的view的时候首先触发的是view的dispatchtouchevent事件。源码如下:
/** * pass the touch screen motion event down to the target view, or this * view if it is the target. * * @param event the motion event to be dispatched. * @return true if the event was handled by the view, false otherwise. */ public boolean dispatchtouchevent (motionevent event) { if (montouchlistener != null && ( mviewflags & enabled_mask) == enabled && montouchlistener.ontouch( this, event)) { return true; } return ontouchevent(event); }
上面的montouchlistener 就是我们在activity中设置的touch事件,我们设置的时候在ontouch中返回的是false,所以会接着执行下面的ontouchevent方法,可以看出ontouchevent的返回值就是dispatchtouchevent 的返回值。ontouchevent这个方法源码比较长,我截断了。
public boolean ontouchevent(motionevent event) { 。。。。。。。。。。。 此处有省略 if (((viewflags & clickable) == clickable || (viewflags & long_clickable) == long_clickable)) { switch (event.getaction()) { 。。。。。。。。。。。 此处有省略 } return true; } return false; }
第4行就是判断该view是否是可点击或者可长按的,如果是返回true。在ontouchevent中先执行action_down(手指按下),如果返回true,那么dispatchtouchevent 的返回值也就是true,就可以接着执行后面的action_move和action_up方法。如果返回false,那么后面的action_move和action_up就不执行了,这个具体原因我还不知道,如果有知道的可以分享下。
说明 1:长按事件是在ontouchevent中的action_down中触发的(如果你设置了长按事件),而点击onclick事件是在action_up中触发的。
现在分析下前面的例子:
由于button默认是可点击的,所以在ontouchevent中会返回true,所以dispatchtouchevent 也会返回true,后面的action_move和action_up可以接着执行。
而textview默认是不可点击的所以ontouchevent中会返回false,那么dispatchtouchevent 也会返回false,后面的action_move和action_up就执行不到了,和上面打印的log相符。
如果我们在activity中对textview设置ontouch事件返回true,结果会怎么样呢,我们先就着dispatchtouchevent 的源码分析下:
mtextview.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { return true; } });
由于返回true,我们从dispatchtouchevent 源码的第10行可以看出montouchlistener.ontouch( this, event))即返回true,那么if条件就成立了,dispatchtouchevent 直接返回true,接着执行后面的action_move和action_up,(action_move如果你点击的时候滑动了才会执行)。但是后面的ontouchevent就执行不到了。
log如下:
没有执行action_move是因为我快速点击且没有滑动,从log可以看出执行完dispatchtouchevent 的action_down之后又执行了dispatchtouchevent 的action_up。但并没有执行ontouchevent。
下面开始讲主题了,也就是前言交代的问题。下面是我自定义的viewgroup:
public class mylinearlayout extends linearlayout { private final static string tag = "mylinearlayout :"; public mylinearlayout(context context, attributeset attrs) { super(context, attrs); // todo auto-generated constructor stub } @override public boolean dispatchtouchevent(motionevent ev) { // todo auto-generated method stub int action = ev.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "dispatchtouchevent , action_down"); break; case motionevent.action_move: log.e(tag, "dispatchtouchevent , action_move"); break; case motionevent.action_up: log.e(tag, "dispatchtouchevent , action_up"); break; default: break; } return super.dispatchtouchevent(ev); } @override public boolean onintercepttouchevent(motionevent ev) { // todo auto-generated method stub int action = ev.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "onintercepttouchevent , action_down"); //return true; break; case motionevent.action_move: log.e(tag, "onintercepttouchevent , action_move"); //return true; break; case motionevent.action_up: log.e(tag, "onintercepttouchevent , action_up"); break; default: break; } return super.onintercepttouchevent(ev); //return true; } @override public boolean ontouchevent(motionevent event) { // todo auto-generated method stub int action = event.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "ontouchevent , action_down"); //return true; break; case motionevent.action_move: log.e(tag, "ontouchevent , action_move"); break; case motionevent.action_up: log.e(tag, "ontouchevent , action_up"); break; default: break; } return super.ontouchevent(event); } @override public void requestdisallowintercepttouchevent(boolean disallowintercept) { // todo auto-generated method stub log.e(tag, "enter requestdisallowintercepttouchevent"); super.requestdisallowintercepttouchevent(disallowintercept); }
xml如下:
<?xml version="1.0" encoding="utf-8"?> <com.example.test.view.touch.mylinearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id="@+id/id_my_linearlayout" > <com.example.test.view.touch.mybutton android:id="@+id/btn_click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="click me" /> <com.example.test.view.touch.mytextview android:id="@+id/my_textview_click" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="textview click" android:textsize="30sp" /> </com.example.test.view.touch.mylinearlayout>
mainactivity如下:
package com.example.test.view.touch; import com.example.drawview.r; import android.app.activity; import android.os.bundle; import android.provider.telephony.mms; import android.util.log; import android.view.motionevent; import android.view.view; import android.view.view.onclicklistener; import android.view.view.ontouchlistener; import android.widget.button; import android.widget.linearlayout; import android.widget.textview; public class testviewgroupetouchactivity extends activity { private final static string tag = "testviewgroupetouchactivity : "; private button mbutton ; private textview mtextview; private linearlayout mlinearlayout ; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.my_linear_layout); mbutton = (button) findviewbyid(r.id.btn_click); mtextview = (textview) findviewbyid(r.id.my_textview_click); mlinearlayout = (linearlayout) findviewbyid(r.id.id_my_linearlayout); mlinearlayout.setonclicklistener(new onclicklistener() { @override public void onclick(view v) { // todo auto-generated method stub log.e(tag, "mlinearlayout , onclick"); } }); mlinearlayout.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub int action = event.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "mlinearlayout , ontouch action_down"); break; case motionevent.action_move: log.e(tag, "mlinearlayout , ontouch action_move"); break; case motionevent.action_up: log.e(tag, "mlinearlayout ,ontouch action_up"); break; default: break; } return false; } }); mbutton.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub int action = event.getaction(); switch (action) { case motionevent.action_down: log.e(tag, "mbutton ontouch action_down"); break; case motionevent.action_move: log.e(tag, "mbutton ontouch action_move"); break; case motionevent.action_up: log.e(tag, "mbutton ontouch action_up"); break; default: break; } return false; } }); mtextview.setontouchlistener(new ontouchlistener() { @override public boolean ontouch(view v, motionevent event) { // todo auto-generated method stub switch (event.getaction()) { case motionevent.action_down: log.e(tag, "mtextview , ontouch action_down"); break; case motionevent.action_move: log.e(tag, "mtextview , ontouch action_move"); break; case motionevent.action_up: log.e(tag, "mtextview , ontouch action_up"); break; default: break; } return false; } }); } }
说明2: 由于我是为了说明前言里面的问题,所以viewgroup的touch事件分发,我不作过多的说明。viewgroup事件分发的流程是:dispatchtouchevent–>onintercepttouchevent—>然后到手指点击view的事件分发(参考上面所说的view的事件分发)。
onintercepttouchevent默认返回false,表示是否拦截事件。viewgroup的dispatchtouchevent的源码如下:
/** * {@inheritdoc} */ @override public boolean dispatchtouchevent(motionevent ev) { final int action = ev.getaction(); final float xf = ev.getx(); final float yf = ev.gety(); final float scrolledxfloat = xf + mscrollx; final float scrolledyfloat = yf + mscrolly; final rect frame = mtemprect; //这个值默认是false, 然后我们可以通过requestdisallowintercepttouchevent(boolean disallowintercept)方法 //来改变disallowintercept的值 boolean disallowintercept = (mgroupflags & flag_disallow_intercept) != 0; //这里是action_down的处理逻辑 if (action == motionevent.action_down) { //清除mmotiontarget, 每次action_down都很设置mmotiontarget为null if (mmotiontarget != null) { mmotiontarget = null; } //disallowintercept默认是false, 就看viewgroup的onintercepttouchevent()方法 if (disallowintercept || !onintercepttouchevent(ev)) { ev.setaction(motionevent.action_down); final int scrolledxint = (int) scrolledxfloat; final int scrolledyint = (int) scrolledyfloat; final view[] children = mchildren; final int count = mchildrencount; //遍历其子view for (int i = count - 1; i >= 0; i--) { final view child = children[i]; //如果该子view是visible或者该子view正在执行动画, 表示该view才 //可以接受到touch事件 if ((child.mviewflags & visibility_mask) == visible || child.getanimation() != null) { //获取子view的位置范围 child.gethitrect(frame); //如touch到屏幕上的点在该子view上面 if (frame.contains(scrolledxint, scrolledyint)) { // offset the event to the view's coordinate system final float xc = scrolledxfloat - child.mleft; final float yc = scrolledyfloat - child.mtop; ev.setlocation(xc, yc); child.mprivateflags &= ~cancel_next_up_event; //调用该子view的dispatchtouchevent()方法 if (child.dispatchtouchevent(ev)) { // 如果child.dispatchtouchevent(ev)返回true表示 //该事件被消费了,设置mmotiontarget为该子view mmotiontarget = child; //直接返回true return true; } // the event didn't get handled, try the next view. // don't reset the event's location, it's not // necessary here. } } } } } //判断是否为action_up或者action_cancel boolean isuporcancel = (action == motionevent.action_up) || (action == motionevent.action_cancel); if (isuporcancel) { //如果是action_up或者action_cancel, 将disallowintercept设置为默认的false //假如我们调用了requestdisallowintercepttouchevent()方法来设置disallowintercept为true //当我们抬起手指或者取消touch事件的时候要将disallowintercept重置为false //所以说上面的disallowintercept默认在我们每次action_down的时候都是false mgroupflags &= ~flag_disallow_intercept; } // the event wasn't an action_down, dispatch it to our target if // we have one. final view target = mmotiontarget; //mmotiontarget为null意味着没有找到消费touch事件的view, 所以我们需要调用viewgroup父类的 //dispatchtouchevent()方法,也就是view的dispatchtouchevent()方法 if (target == null) { // we don't have a target, this means we're handling the // event as a regular view. ev.setlocation(xf, yf); if ((mprivateflags & cancel_next_up_event) != 0) { ev.setaction(motionevent.action_cancel); mprivateflags &= ~cancel_next_up_event; } return super.dispatchtouchevent(ev); } //这个if里面的代码action_down不会执行,只有action_move //action_up才会走到这里, 假如在action_move或者action_up拦截的 //touch事件, 将action_cancel派发给target,然后直接返回true //表示消费了此touch事件 if (!disallowintercept && onintercepttouchevent(ev)) { final float xc = scrolledxfloat - (float) target.mleft; final float yc = scrolledyfloat - (float) target.mtop; mprivateflags &= ~cancel_next_up_event; ev.setaction(motionevent.action_cancel); ev.setlocation(xc, yc); if (!target.dispatchtouchevent(ev)) { } // clear the target mmotiontarget = null; // don't dispatch this event to our own view, because we already // saw it when intercepting; we just want to give the following // event to the normal ontouchevent(). return true; } if (isuporcancel) { mmotiontarget = null; } // finally offset the event to the target's coordinate system and // dispatch the event. final float xc = scrolledxfloat - (float) target.mleft; final float yc = scrolledyfloat - (float) target.mtop; ev.setlocation(xc, yc); if ((target.mprivateflags & cancel_next_up_event) != 0) { ev.setaction(motionevent.action_cancel); target.mprivateflags &= ~cancel_next_up_event; mmotiontarget = null; } //如果没有拦截action_move, action_down的话,直接将touch事件派发给target return target.dispatchtouchevent(ev); }
当我们点击button的时候,由于我们activity中重写的onintercepttouchevent返回值为super.onintercepttouchevent(ev);即默认的false,那么25行的if条件!onintercepttouchevent(ev))为true。进入if语句里面,遍历所有的子view,然后执行51行的if (child.dispatchtouchevent(ev)),上面讲到了button是可点击的,那么mybutton的ontouchevent返回值为true,即dispatchtouchevent返回值为true。消费了该事件,所有不会触发mlinearlayout的点击事件。log如下:
那么问题来了,为什么将mybutton 的ontouchevent返回值设为false,然后点击button就会触发mlinearlayout的点击事件呢?
我们来分析下:将mybutton 的ontouchevent返回值设为false,那么51行的if (child.dispatchtouchevent(ev))的返回值为false,为什么呢?
上面分析view的dispatchtouchevent源码时分析过了。 返回了false,那么看viewgroup的源码,81行, final view target = mmotiontarget; 由于51行的if (child.dispatchtouchevent(ev))返回false,所以没有对mmotiontarget进行赋值, mmotiontarget == null。
所以走到85行:if (target == null) //target = mmotiontarget ,所以该if条件成立。
走到93行:return super.dispatchtouchevent(ev);
执行第9行的super.dispatchtouchevent(ev),viewgroup的super是view,即执行view的dispatchtouchevent方法。由于我们在activity中47行设置了ontouch事件,所以先执行activity 中 mlinearlayout.setontouchlistener中的ontouch, ontouch返回false ,接着执行 mylinearlayout 中的ontouchevent。
说明:
本来由于mylinearlayout 是继承自linearlayout,默认和textview一样是没有点击(clickable)或长按(longclickable)的能力的。但是,我们在activity的38行对他设置了点击事件,mlinearlayout.setonclicklistener,所以mylinearlayout 获得 点击的能力。
所以mylinearlayout的ontouchevent返回true,然后执行mylinearlayout的ontouchevent的action_up,而点击事件就是在action_up中执行的(说明1)。所有触发了mlinearlayout.setonclicklistener点击事件。log 如下:
总结:
1.touch事件是从顶层的view一直往下分发到手指按下的最里面的view,如果这个view的ontouchevent()返回false,即不消费touch事件,这个touch事件就会向上找父布局调用其父布局的ontouchevent()处理,如果这个view返回true,表示消费了touch事件,就不调用父布局的ontouchevent()。
2.一个clickable或者longclickable的view会永远消费touch事件,不管他是enabled还是disabled的。
3.view的长按事件是在action_down中执行,要想执行长按事件该view必须是longclickable的,如果设置的长按事件中返回true,那么clickable事件不会触发。并且不能产生action_move。
4.view的点击事件是在action_up中执行,想要执行点击事件的前提是消费了action_down和action_move,并且是在没有设置onlongclicklistener的情况下,如设置了onlongclicklistener的情况,则必须使onlongclick()返回false。
5.如果view设置了ontouchlistener了,并且ontouch()方法返回true,则不执行view的ontouchevent()方法,也表示view消费了touch事件,返回false则继续执行ontouchevent()。
6.touch事件是从最顶层的view一直分发到手指touch的最里层的view,如果最里层view消费了action_down事件(设置ontouchlistener,并且ontouch()返回true 或者ontouchevent()方法返回true)才会触发action_move,action_up的发生,如果某个viewgroup拦截了touch事件,则touch事件交给viewgroup处理。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。