Android事件的分发机制
在分析Android事件分发机制前,明确android的两大基础控件类型:View和ViewGroup。View即普通的控件,没有子布局的,如Button、TextView. ViewGroup继承自View,表示可以有子控件,如Linearlayout、Listview这些。今天我们先来了解View的事件分发机制。
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.i("Tag", "This is button onClick event");
}
});
btn.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("Tag", "This is button onTouch action" + event.getAction());
return false;
}
});
运行一下项目,结果如下:
I/Tag: This is button onTouch action0
I/Tag: This is button onTouch action2
I/Tag: This is button onTouch action2
I/Tag: This is button onTouch action1
I/Tag: This is button onClick event
可以看到,onTouch是有先于onClick执行的,因此事件的传递顺序是先onTouch,在到OnClick。具体为什么这样,下面会通过源码来说明。这时,我们可能注意到了,onTouch的方法是有返回值,这里是返回false,我们将它改为true再运行一次,结果如下:
I/Tag: This is button onTouch action0
I/Tag: This is button onTouch action2
I/Tag: This is button onTouch action2
I/Tag: This is button onTouch action2
I/Tag: This is button onTouch action1
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)) {
//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;
}
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// 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)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
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();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0);
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
从源码的21行我们可以看出,该控件可点击就会进入到switch判断中,当我们触发了手指离开的实际,则会进入到MotionEvent.ACTION_UP这个case当中。我们接着往下看,在源码的50行,调用到了mPerformClick()方法,我们继续进入到这个方法的源码看看。
public boolean performClick() {
final boolean result;
final ListenerInfo li = mListenerInfo;
if (li != null && li.mOnClickListener != null) {
playSoundEffect(SoundEffectConstants.CLICK);
li.mOnClickListener.onClick(this);
result = true;
} else {
result = false;
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
return result;
}
现在我们可以看到,只要ListenerInfo和mOnClickListener不为null就会调用onClick这个方法,之前说过,只要有监听事件,ListenerInfo就不为null,带mOnClickListener又是在哪里赋值呢?我们再继续看下它的源码。
public void setOnClickListener(@Nullable OnClickListener l) {
if (!isClickable()) {
setClickable(true);
}
getListenerInfo().mOnClickListener = l;
}
看到这里一切就清楚了,当我们调用setOnClickListener方法来给按钮注册一个点击事件时,就会给mOnClickListener赋值。整个分发事件的顺序是onTouch()-->onTouchEvent(event)-->performClick()-->OnClick()。
现在我们可以解决之前的问题。
1、onTouch方法是优先于OnClick,所以是执行了onTouch,再执行onClick。
2、无论是dispatchTouchEvent还是onTouchEvent,如果返回true表示这个事件已经被消费、处理了,不再往下传了。在dispathTouchEvent的源码里可以看到,如果onTouchEvent返回了true,那么它也返回true。如果dispatchTouchEvent在执行onTouch监听的时候,onTouch返回了true,那么它也返回true,这个事件提前被onTouch消费掉了。就不再执行onTouchEvent了,更别说onClick监听了。
Android事件的分发机制的更多相关文章
- Android NestedScrolling与分发机制
在Android5.0之间要实现控件的嵌套滑动,都是要自己处理View事件即分发机制. 共有三个方法: dispatchTouchEvent().onInterceptTouchEvent()和 ...
- View,ViewGroup的Touch事件的分发机制
原帖地址:http://blog.csdn.net/xiaanming/article/details/21696315 ViewGroup的事件分发机制 我们用手指去触摸Android手机屏幕,就会 ...
- Andriod 从源码的角度详解View,ViewGroup的Touch事件的分发机制
转自:xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/21696315) 今天这篇文章主要分析的是Android的事件分发机制, ...
- Android事件总线分发库EventBus3.0的简单讲解与实践
Android事件总线分发库EventBus的简单讲解与实践 导语,EventBus大家应该不陌生,EventBus是一款针对Android优化的发布/订阅事件总线.主要功能是替代Intent,Han ...
- Android NestedScrolling与分发机制 二
上篇转载了 Android:30分钟弄明白Touch事件分发机制 这篇转载 Android中的dispatchTouchEvent().onInterceptTouchEvent()和onTouchE ...
- android事件拦截处理机制详解
前段时间刚接触过Android手机开发,对它的事件传播机制不是很了解,虽然网上也查了相关的资料,但是总觉得理解模模糊糊,似是而非,于是自己就写个小demo测试了一下.总算搞明白了它的具体机制.写下自己 ...
- 45、Android事件总线分发库的使用
事件总线分发库EventBus和Otto的简介及对比 什么是事件总线管理: a.将事件放到队列里,用于管理和分发b.保证应用的各个部分之间高效的通信及数据.事件分发c.模块间解耦 Event Bus是 ...
- android事件拦截处理机制具体解释
前段时间刚接触过android手机开发.对它的事件传播机制不是非常了解,尽管网上也查了相关的资料,可是总认为理解模模糊糊,似是而非,于是自己就写个小demo測试了一下. 总算搞明确了它的详细机制.写下 ...
- touch事件的分发机制
作者:谢昆 一段伪代码反应整个touch事件的分发 public boolean dispatchTouchEvent(MotionEvent event) { boolean consume = f ...
随机推荐
- python自学笔记
python自学笔记 python自学笔记 1.输出 2.输入 3.零碎 4.数据结构 4.1 list 类比于java中的数组 4.2 tuple 元祖 5.条件判断和循环 5.1 条件判断 5.2 ...
- java测试1
发大水 package com.java1234.activiti.variable; import java.util.Date; import java.util.HashMap; import ...
- ASP.NET MVC中的模型绑定
模型绑定的本质 任何控制器方法的执行都受action invoker组件(下文用invoker代替)控制.对于每个Action方法的参数,这个invoker组件都会获取一个Model Binder ...
- locate 不能使用
当需要查找一个文件,只知道文件名不知道路径,我们通常用locate,由于公司的服务器使用最小化安装的所以当locate 文件名,报错,提 示-bash: locate: command not fou ...
- 代码发布架构方案(SVN)
问题: 安装优化软件环境nginx,lvs 程序代码(不断更新) 配置更新(不断变更) 1.SVN介绍 1.1 什么是SVN(Subversion)? SVN(Subversion) ...
- insert 和 if x is not None
insert(位置,元素) #!/usr/bin/python aList = [123, 'xyz', 'zara', 'abc'] aList.insert( 3, 2009) print &qu ...
- codevs4373 窗口
题目描述 Description 给你一个长度为N的数组,一个长为K的滑动的窗体从最左移至最右端,你只能见到窗口的K个数,每次窗体向右移动一位,如下表: Window position Min val ...
- process launch failed : failed to get the task for process xxx
原因: 证书问题,project和targets的证书都必须是开发证书,ADHOC的证书会出现此问题. 解决方案: project和targets的证书使用开发证书. 其他: This error ...
- java.util.concurrent并发包诸类概览
java.util.concurrent包的类都来自于JSR-166:Concurrent Utilities,官方的描述叫做“The JSR proposes a set of medium-lev ...
- ZedGraph控件生成饼图、拆线图和柱状图例程
这几天做了个自己觉得还蛮NB的功能,在GRID中选中一块数据,然后右键菜单即可生成三种图形,还可以互相切换,对了,饼图还添加了鼠标点击分离的处理,大致如图: 用的控件就是ZedGraph,我把它继承封 ...