Android的事件分发机制的实验(亲测)
网上关于Android触摸事件的分发机制的文章有很多,但是我怀疑很多文章是错误的,所以今天亲自测试了一下事件的分发的流程,摸索出一些规律,如果对本文实验结果有所质疑欢迎大家提出并指正,实验记录如下:
申明:如需转载请声明出处,请尊重他人劳动,谢谢合作
实验图如下:
大家可以看到这个Activity中有四个View 从里到外分别是view_1(relativeLayout),view_2(relativeLayout),
view_3(relativeLayout),view_4(Button).
实验方法:
package com.example.androidges; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.Button; public class MyButton extends Button{ int id = 0; public MyButton(Context context) { super(context); // TODO Auto-generated constructor stub } public MyButton(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public MyButton(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub boolean b = super.onTouchEvent(event); //b = false; System.out.println("view_" + id +" onTouchEvent " + event.getAction() + ":" + b); return b; } @Override public boolean dispatchTouchEvent(MotionEvent event) { // TODO Auto-generated method stub boolean b = super.dispatchTouchEvent(event); System.out.println("view_" + id +" dispatchTouchEvent " + event.getAction()+ ":" + b); return b; } }
MyLayout.java
package com.example.androidges; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.RelativeLayout; public class MyLayout extends RelativeLayout{ int id = 0; public MyLayout(Context context) { super(context); // TODO Auto-generated constructor stub } public MyLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } public MyLayout(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override public boolean dispatchTouchEvent(MotionEvent event) { // TODO Auto-generated method stub boolean b = super.dispatchTouchEvent(event); //if(id == 2) b = false; System.out.println( "view_" + id + " dispatchTouchEvent " + event.getAction()+ ":" + b); return b; } @Override public boolean onInterceptTouchEvent(MotionEvent event) { // TODO Auto-generated method stub boolean b = super.onInterceptTouchEvent(event); //if(id == 3) b = true; System.out.println("view_" + id + " onInterceptTouchEvent " + event.getAction()+ ":" + b); return b; } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub boolean b = super.onTouchEvent(event); //if(id == 3) b = true; System.out.println("view_" + id + " onTouchEvent " + event.getAction()+ ":" + b); return b; } }
说明一下:id是用来标记View用的,方便在Log中查看当前是View 1234中的哪一个。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。