触摸事件

两种检测触摸事件的方式:

  • 设置触摸监听  setOnTouchListener
返回 true: 表示消费事件 , 可以检测到 down/move/up 事件
返回 false: 不消费事件, 只能检测到 down 事件
  • 重写onTouchEvent()
必须继承自系统的一个View,才能重写 onTouchEvent()方法;
如 MyImageView extends ImageView ,才能重写onTouchEvent
返回 true: 消费事件,能检测到 down/move/up 事件
返回 false: 不消费事件,只能检测到 down 事件

如果两种触摸事件都存在,并且都返回true,结果如何?

setOnTouchListener 有效
onTouchEvent() 无效
另外:一个View能否消费事件,关键看 dispatchTouchEvent(),我们来看下 android-10的源码(为什么要看这个版本的源码呢?因为低版本的源码中,原理性的知识点都是一样的,高版本的源码中,加入了非常多的逻辑判断) 
View.java事件是怎么分发的
    /*** 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);}
我们可以看到如果两种方式都设置的话,每次这个if条件判断都会走,所以 onTouchListener 可以拿到所有事件(down/move/up事件);只有onTouchListener返回false时,onTouchEvent()方法才会走,才能拿到(down/move/up)所有事件;

如何让两种方式同时生效呢?

setOnTouchListener  返回false
onTouchEvent() 返回true
下面我们上代码:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.xialm.touchdemo.MainActivity"><ImageViewandroid:id="@+id/iv"android:layout_width="100dp"android:layout_height="100dp"android:src="@mipmap/ic_launcher" />
</RelativeLayout>

修改返回true,所有事件都能拿到;返回false,只能拿到down事件;
true时:
04-28 01:44:13.515 1471-1471/com.xialm.touchdemo E/MainActivity: onTouch: 0
04-28 01:44:18.266 1471-1471/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:44:18.283 1471-1471/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:44:18.333 1471-1471/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:44:19.555 1471-1471/com.xialm.touchdemo E/MainActivity: onTouch: 1

false时:
04-28 01:44:13.515 1471-1471/com.xialm.touchdemo E/MainActivity: onTouch: 0

同理,我们创建 CustomImageView,继承自ImageView,同时修改布局文件中的ImageView为 CustomImageView
public class CustomImageView extends ImageView {private static final String TAG = "CustomImageView";public CustomImageView(Context context) {super(context);}public CustomImageView(Context context, AttributeSet attrs) {super(context, attrs);}public CustomImageView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}/*** 返回false:只能拿到down事件* 返回true: 能拿到down/move/up事件* @param event* @return*/@Overridepublic boolean onTouchEvent(MotionEvent event) {Log.e(TAG, "onTouchEvent: "+event.getAction() );return true; //super.onTouchEvent(event);}
}

同时设置,同时返回true的情况,可以看到跟我们的分析是一样的

04-28 01:47:54.060 5005-5005/com.xialm.touchdemo E/MainActivity: onTouch: 0
04-28 01:47:54.434 5005-5005/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:47:54.450 5005-5005/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:47:54.817 5005-5005/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:47:54.850 5005-5005/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:47:55.188 5005-5005/com.xialm.touchdemo E/MainActivity: onTouch: 1

同时设置setOnTouchListener返回false,onTouchEvent()返回true

04-28 01:49:55.452 6978-6978/com.xialm.touchdemo E/MainActivity: onTouch: 0
04-28 01:49:55.452 6978-6978/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 0
04-28 01:49:58.850 6978-6978/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:49:58.850 6978-6978/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 01:49:58.866 6978-6978/com.xialm.touchdemo E/MainActivity: onTouch: 2
04-28 01:49:58.866 6978-6978/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 01:49:59.926 6978-6978/com.xialm.touchdemo E/MainActivity: onTouch: 1
04-28 01:49:59.926 6978-6978/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 1

Touch事件处理流程分析

我们自定义一个MyLinearLayout 继承自系统的LinearLayout,然后在布局文件中包裹 CustomImageView,

public class MyLinearLayout extends LinearLayout {private static final String TAG = "MyLinearLayout";public MyLinearLayout(Context context) {super(context);}public MyLinearLayout(Context context, AttributeSet attrs) {super(context, attrs);}public MyLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}@Overridepublic boolean onTouchEvent(MotionEvent event) {Log.e(TAG, "onTouchEvent: "+event.getAction() );return true;//super.onTouchEvent(event);   返回true}
}
<com.xialm.touchdemo.MyLinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="#ccc"android:padding="10dp"><com.xialm.touchdemo.CustomImageViewandroid:id="@+id/iv"android:layout_width="100dp"android:layout_height="100dp"android:src="@mipmap/ic_launcher" /></com.xialm.touchdemo.MyLinearLayout>

我们只研究onTouchEvent()

CustomImageView的onTouchEvent()也返回true

04-28 02:37:15.952 14101-14101/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 0
04-28 02:37:16.350 14101-14101/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:37:16.367 14101-14101/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:37:16.700 14101-14101/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:37:17.367 14101-14101/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:37:17.648 14101-14101/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 1

当父View和子view都有处理触摸事件的逻辑时,子view可以接收到所有的事件;

这是因为事件传递是由外向内,而事件的消费是由内向外的;

只有子View不处理触摸事件时,父View才能处理消费事件(即CustomImageView的onTouchEvent()返回false,MyLinearLayout的onTouchEvent()返回true)
使用下面示意图来解释,再好不过了:

父View想要消费事件,有没有办法呢?
办法是有的,只需重写onInterceptTouchEvent()方法,返回true,把事件中断掉,则事件就不能往下传递了,我们处理消费逻辑即可:
public class CustomImageView extends ImageView {...省略代码.../*** 返回false:只能拿到down事件* 返回true: 能拿到down/move/up事件* @param event* @return*/@Overridepublic boolean onTouchEvent(MotionEvent event) {Log.e(TAG, "onTouchEvent: "+event.getAction() );return true; //super.onTouchEvent(event);}
}

public class MyLinearLayout extends LinearLayout {...省略代码...private int count = 0;@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {count++;if (count > 4) {return true;}return false; // 中断事件}@Overridepublic boolean onTouchEvent(MotionEvent event) {Log.e(TAG, "onTouchEvent: "+event.getAction() );return true;//super.onTouchEvent(event);}
}

04-28 02:52:30.948 28332-28332/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 0
04-28 02:52:31.250 28332-28332/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:52:31.266 28332-28332/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:52:31.783 28332-28332/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 2
04-28 02:52:31.800 28332-28332/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 3
04-28 02:52:31.867 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 2
04-28 02:52:31.933 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 2
04-28 02:52:31.950 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 2
04-28 02:52:32.033 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 2
04-28 02:52:32.050 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 2
04-28 02:52:32.167 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 2
04-28 02:52:35.396 28332-28332/com.xialm.touchdemo E/MyLinearLayout: onTouchEvent: 1

由下面流程示意图来说明:

触摸事件与点击事件

onTouchEvent() 与 onClickListener

点击事件是由 down 和 up 事件组成的,系统一直检测 up事件是否发生,如果有up事件,就会判断 onClickListener监听是否存在,存在就回调onClick()方法
触摸事件和点击事件同时存在时:
系统是怎么区分点击事件还是触摸事件呢?不知道你有没有注意到我们重写onTouchEvent()时有一句话

super.onTouchEvent(event); // 在内部处理了,点击事件的逻辑

查看android-10 View.java源码 我们着重留意一下 up事件
 /*** Implement this method to handle touch screen motion events.** @param event The motion event.* @return True if the event was handled, false otherwise.*/public boolean onTouchEvent(MotionEvent event) {final int viewFlags = mViewFlags;if ((viewFlags & ENABLED_MASK) == DISABLED) {// A disabled view that is clickable still consumes the touch// events, it just doesn't respond to them.return (((viewFlags & CLICKABLE) == CLICKABLE ||(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));}if (mTouchDelegate != null) {if (mTouchDelegate.onTouchEvent(event)) {return true;}}if (((viewFlags & CLICKABLE) == CLICKABLE ||(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {switch (event.getAction()) {case MotionEvent.ACTION_UP:    // 着重研究up事件if ((mPrivateFlags & PRESSED) != 0) {// 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 (!mHasPerformedLongPress) {// This is a tap, so remove the longpress checkif (mPendingCheckForLongPress != null) {removeCallbacks(mPendingCheckForLongPress);}// Only perform take click actions if we were in the pressed stateif (!focusTaken) {performClick();  // 执行点击监听回调}}if (mUnsetPressedState == null) {mUnsetPressedState = new UnsetPressedState();}if (!post(mUnsetPressedState)) {// If the post failed, unpress right nowmUnsetPressedState.run();}}break;case MotionEvent.ACTION_DOWN:mPrivateFlags |= PRESSED;refreshDrawableState();if ((mViewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) {postCheckForLongClick();}break;case MotionEvent.ACTION_CANCEL:mPrivateFlags &= ~PRESSED;refreshDrawableState();break;case MotionEvent.ACTION_MOVE:final int x = (int) event.getX();final int y = (int) event.getY();// Be lenient about moving outside of buttonsint slop = ViewConfiguration.get(mContext).getScaledTouchSlop();if ((x < 0 - slop) || (x >= getWidth() + slop) ||(y < 0 - slop) || (y >= getHeight() + slop)) {// Outside buttonif ((mPrivateFlags & PRESSED) != 0) {// Remove any future long press checksif (mPendingCheckForLongPress != null) {removeCallbacks(mPendingCheckForLongPress);}// Need to switch from pressed to not pressedmPrivateFlags &= ~PRESSED;refreshDrawableState();}} else {// Inside buttonif ((mPrivateFlags & PRESSED) == 0) {// Need to switch from not pressed to pressedmPrivateFlags |= PRESSED;refreshDrawableState();}}break;}return true;}return false;}

    /*** Call this view's OnClickListener, if it is defined.** @return True there was an assigned OnClickListener that was called, false*         otherwise is returned.*/public boolean performClick() {sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);if (mOnClickListener != null) {  // 点击监听回调不为null,就执行回调,并返回trueplaySoundEffect(SoundEffectConstants.CLICK);mOnClickListener.onClick(this);return true;}return false;}

如果我们想要同时处理点击事件和触摸事件,super.onTouchEvent(event); 就不可少

  @Overridepublic boolean onTouchEvent(MotionEvent event) {super.onTouchEvent(event);Log.e(TAG, "onTouchEvent: "+event.getAction() );return true;}
04-28 03:40:08.296 8330-8330/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 0
04-28 03:40:08.392 8330-8330/com.xialm.touchdemo E/CustomImageView: onTouchEvent: 1
04-28 03:40:08.393 8330-8330/com.xialm.touchdemo E/MainActivity: onClick: 

Android 中触摸事件与点击事件分析相关推荐

  1. Android中的事件处理之点击事件

    在 Android 的图形界面(UI)开发中,有两个非常重要的内容∶一个是控件的布局,另个就是控件的事件处理.Android中的常用事件有点击事件.长按事件.触摸事件.焦点事件.按键事件-下拉列表的选 ...

  2. android webview 自动点击事件,Android中的WebView布局点击事件的方法

    继承WebView自定义一个MyWebView,然后重载它的onTouchEvent方法,就可以解决了. public class MyWebView extends WebView{ public ...

  3. android通知栏的点击事件,Android监听消息通知栏点击事件

    Android监听消息通知栏点击事件 使用BroadCastReceiver 1 新建一个NotificationClickReceiver 类,并且在清单文件中注册!! public class N ...

  4. Android 动态添加标签及其点击事件

    在做Android开发的时候,会遇到动态添加标签让用户选择的功能,所以自己写了个例子,运行效果图如下. 标签可以左右滑动进行选择,点击的时候,会弹出toast提示选择或者取消选择了哪个标签.通过动态添 ...

  5. iostext添加点击事件_iOS开发小技巧 - label中的文字添加点击事件

    Label中的文字添加点击事件 以前老师讲过类似的功能,自己懒得回头看了,找了很多第三方的,感觉这个小巧便利,作者只是扩展了分类,实现起来代码也少.先来个效果图 自己的项目,直接上代码 - (void ...

  6. ListView的长按事件和点击事件冲突的解决办法

    需求是这样的:listView中点击item 跳转到一个activity,长按item可以对这条item进行删除操作,在删除前会弹出dialog(确认删除对话框). 但是在开发过程中发现,当长按某个i ...

  7. Android在WebView中给图片设置点击事件

    好久没有更新博客了,今天来个小知识点.我们知道在WebView中加载的是Html也面,在开发中都是Web前端人员写好以后给个链接我们去用webView进行loadUrl.但是有时突然产品想让你把加载回 ...

  8. Android 中Touch(触屏)事件传递机制

    版本:2.0 日期:2014.3.21 2014.3.29 版权:© 2014 kince 转载注明出处 一.基本概念 在实际开发中,经常会遇到与触屏事件有关的问题,最典型的一个就是滑动冲突.比如在使 ...

  9. Android viewpager 嵌套 viewpager滑动 点击事件冲突解决方案

    为了解决这个问题.可以自定义viewpager,然后在里面监听首饰,自定义点击事件 package com.hpuvoice.view;import android.content.Context; ...

最新文章

  1. Opencv中的FaceRecognizer类
  2. Win10 安装程序错误2502/2503 拒绝访问 解决
  3. lmdb简介——结合MVCC的B+树嵌入式数据库
  4. 使用poi进行数据的导出Demo
  5. 【机器学习基础】前置知识(一):数学符号及希腊字母
  6. 《02》let 和 const 命令
  7. csky linux 编译内核,TQ2440的EmbedSky_hello模块编译内核问题及解决
  8. php preg_match_all匹配正则,字符串过长时出错
  9. 自动化SQL Server Analysis Server表格模型的文档
  10. spring.net 对象创建 几种情况
  11. js - 预加载+监听图片资源加载制作进度条
  12. php soapenv:server.userexception,SoapFault - faultcode: 'soap:Server' faultstring
  13. IplImage结构及与其相关的读写函数
  14. 海康门禁C# demo-开,关,常开,常关,授权,清权
  15. 贴片钽电容封装及规格参数资料
  16. 人体神经系统分布图高清,神经分布图超清图片
  17. 软件工程——软件开发过程中用到的各种图
  18. 转:年轻员工不听话?可能是他们想听的话和以前不同了
  19. py脚本检索指定文件并发送邮件+脚本打包、伪装
  20. 计算机之魂计算机软件系统教学设计,大连理工版信息技术八上《计算机之魂——计算机软件系统》教案1.doc...

热门文章

  1. 12. SSL和TLS有关知识
  2. 我国智能变电站建设到什么程度了
  3. DS18b20温度值换算
  4. Excel学习——制作周报
  5. RTL8812F/RTL8197F修改beacon间隔
  6. 51单片机——存储器
  7. Leetcode——153. Find Minimum in Rotated Sorted Array
  8. 国务院办公厅关于2014年部分节假日安排的通知
  9. mvc模式网页购物车
  10. MQ2烟雾传感器模块——stm32f103