什么是Touch事件?java
一个Touch事件在用户点击屏幕(ACTION_DOWN)时产生,抬起手指(ACTION_UP)时结束,而Touch事件又被封装到MotionEvent当中。android
touch事件能够分为如下:安全
事件类型 | 说明 |
---|---|
ACTION_DOWN | 手指按下 |
ACTION_MOVE | 手指移动 |
ACTION_UP | 手指抬起 |
ACTION_POINTER_DOWN | 多手指按下 |
ACTION_POINTER_UP | 多手指抬起 |
ACTION_CANCEL | 取消事件 |
获取事件类型的Action方式最多见的是经过MotionEvent的getAction()方法,getAction()方法能够获ACTION_DONW、ACTION_UP、ACTION_MOVE、以及ACTION_CANCEL等事件,咱们分析事件传递时基本也是分析这些事件。app
ACTION_POINTER_DOWN和ACTION_POINTER_UP,则得和ACTION_MASK相与才能获得。ide
...源码分析
class TestView : View {
companion object {
val TAG: String = TestView::class.java.simpleName
}
constructor(context: Context) : super(context) {
}
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
Log.d(TAG, "TestView dispatchTouchEvent-------------------------")
return super.dispatchTouchEvent(event)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
Log.d(TAG, "TestView onTouchEvent-------------------------")
return super.onTouchEvent(event)
}
}
复制代码
...ui
...this
class MainActivity : AppCompatActivity() {
companion object {
val TAG: String = MainActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
testView.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
Log.d(TAG, "onTouch ----------------------")
return false
}
})
}
}
复制代码
...spa
当我手指触摸屏幕移动抬起来的时候,后台日志输出rest
...
2019-05-16 14:45:35.601 19010-19010/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:45:35.602 19010-19010/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:45:35.602 19010-19010/com.example.alldemo D/TestView: TestView onTouchEvent-------------------------
复制代码
...
能够看到调用顺序是View.dispatchTouchEvent -> onTouch -> View.onTouchEvent
若是此时我这样设置
...
class MainActivity : AppCompatActivity() {
companion object {
val TAG: String = MainActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
testView.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
Log.d(TAG, "onTouch ----------------------")
return true
}
})
}
}
复制代码
...
直接在setOnTouchListener的回调中return true的时候,此时后台日志
...
2019-05-16 14:56:25.081 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.082 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.095 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.095 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.105 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.105 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.121 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.122 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
2019-05-16 14:56:25.139 19529-19529/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------
2019-05-16 14:56:25.139 19529-19529/com.example.alldemo D/MainActivity: onTouch ----------------------
复制代码
...
此时调用顺序是View.dispatchTouchEvent -> onTouch View.onTouchEvent再也不执行
...
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;
//mOnTouchListener就是例子中设置进去的OnTouchListener
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED
&& li.mOnTouchListener.onTouch(this, event)) {//返回true的话,直接设置 result = true
result = true;
}
//若是result = true的话,那么!result就不成立,直接跳出来,也就是不在执行onTouchEvent了
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;
}
复制代码
...
从代码看View执行的分发流程仍是比较简单的,代码量也很少,下面总结一下View的事件分发流程
'''
class TestViewGroup : LinearLayout {
companion object {
val TAG: String = TestViewGroup::class.java.simpleName
}
constructor(context: Context) : super(context) {
}
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
}
override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
Log.d(TAG, "TestViewGroup onInterceptTouchEvent------------------------- action =" + ev?.action)
return super.onInterceptTouchEvent(ev)
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
Log.d(TAG, "TestViewGroup dispatchTouchEvent------------------------- action =" + event?.action)
return super.dispatchTouchEvent(event)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
Log.d(TAG, "TestViewGroup onTouchEvent------------------------- action =" + event?.action)
return super.onTouchEvent(event)
}
}
复制代码
'''
TestView的代码以下
'''
class TestView : View {
companion object {
val TAG: String = TestView::class.java.simpleName
}
constructor(context: Context) : super(context) {
}
constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) {
}
override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
Log.d(TAG, "TestView dispatchTouchEvent-------------------------action =" + event?.action)
return super.dispatchTouchEvent(event)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
Log.d(TAG, "TestView onTouchEvent-------------------------action =" + event?.action)
return super.onTouchEvent(event)
}
}
复制代码
'''
Activity代码设置以下:
'''
class MainActivity : AppCompatActivity() {
companion object {
val TAG: String = MainActivity::class.java.simpleName
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
testView.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
Log.d(TAG, "testView onTouch ---------------------- action =" + event?.action)
return false
}
})
testViewGroup.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
Log.d(TAG, "testViewGroup onTouch ---------------------- action =" + event?.action)
return false
}
})
}
}
复制代码
'''
运行项目以后,用手指在屏幕触摸一下,后台日志输出以下:
'''
2019-05-16 15:33:34.308 21036-21036/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =0
2019-05-16 15:33:34.308 21036-21036/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =0
2019-05-16 15:33:34.308 21036-21036/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/TestView: TestView onTouchEvent-------------------------action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/MainActivity: testViewGroup onTouch ---------------------- action =0
2019-05-16 15:33:34.309 21036-21036/com.example.alldemo D/TestViewGroup: TestViewGroup onTouchEvent------------------------- action =0
复制代码
'''
若是我此时把Activity的代码这样改动一下:
'''
testView.setOnTouchListener(object : View.OnTouchListener {
override fun onTouch(v: View?, event: MotionEvent?): Boolean {
Log.d(TAG, "testView onTouch ---------------------- action =" + event?.action)
return true
}
})
复制代码
'''
手指触摸,日志输出以下:
'''
2019-05-16 15:42:17.769 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =0
2019-05-16 15:42:17.769 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =0
2019-05-16 15:42:17.770 21890-21890/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =0
2019-05-16 15:42:17.770 21890-21890/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =0
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =2
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup dispatchTouchEvent------------------------- action =1
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestViewGroup: TestViewGroup onInterceptTouchEvent------------------------- action =1
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/TestView: TestView dispatchTouchEvent-------------------------action =1
2019-05-16 15:42:17.806 21890-21890/com.example.alldemo D/MainActivity: testView onTouch ---------------------- action =1
复制代码
'''
说明一下 action=0表明的事件是ACTION_DOWN,action=2表明的事件是ACTION_MOVE,action=1表明的事件是ACTION_UP,
从日志分析,第一次默认的状况下,事件分发是先从TestViewGroup.dispatchTouchEvent -> TestViewGroup.onInterceptTouchEvent -> TestView.dispatchTouchEvent - > testView onTouch -> TestView.onTouchEvent - > testViewGroup onTouch -> TestViewGroup.onTouchEvent
第二次,事件分发是从TestViewGroup.dispatchTouchEvent(ACTION_DOWN) -> TestViewGroup.onInterceptTouchEvent(ACTION_DOWN) ->TestView.dispatchTouchEvent(ACTION_DOWN) ->testView onTouch(ACTION_DOWN) -> TestViewGroup.dispatchTouchEvent(ACTION_MOVE) ->TestViewGroup.onInterceptTouchEvent((ACTION_MOVE)) -> TestView.dispatchTouchEvent(ACTION_MOVE) -> testView onTouch(ACTION_MOVE) -> TestViewGroup.dispatchTouchEvent(ACTION_UP) ->TestViewGroup.onInterceptTouchEvent((ACTION_UP)) -> TestView.dispatchTouchEvent(ACTION_UP) -> testView onTouch(ACTION_UP)
从方法中,ViewGroup的事件分发比View的事件分发多了onInterceptTouchEvent,下面咱们从源码角度来理解一下ViewGroup的事件分发流程
'''
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(ev, 1);
}
//若是事件指向一个可达的那么正常分发
// If the event targets the accessibility focused view and this is it, start
// normal event dispatch. Maybe a descendant is what will handle the click.
if (ev.isTargetAccessibilityFocus() && isAccessibilityFocusedViewOrHost()) {
ev.setTargetAccessibilityFocus(false);
}
boolean handled = false;//是否处理的标志
//安全性检查,返回true才进行
if (onFilterTouchEventForSecurity(ev)) {
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
cancelAndClearTouchTargets(ev);
resetTouchState();
}
// Check for interception.
//是否intercepted的标志,也就是前面提到的ViewGroup比View多的onInterceptTouchEvent方法标志
final boolean intercepted;
//事件开始或者事件已经有target的时候都会进去,由于若是事件不是刚开始并且事件mFirstTouchTarget为空就没有必要判断拦截了,默认拦截
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
//事件没有取消,而且事件没有拦截的状况下,去找子view,看看那个消费了此次事件
if (!canceled && !intercepted) {
// If the event is targeting accessibility focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList<View> preorderedList = buildTouchDispatchChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
//安装倒序找view这个在前面事件视图层级有说到,事件是从内到外传递的
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = getAndVerifyPreorderedIndex(
childrenCount, i, customOrder);
final View child = getAndVerifyPreorderedView(
preorderedList, children, childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//此view有没有占据这次事件,没有继续
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
//查找新的targertview,找到则跳出
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//递归的方式在子child view的子类找是否有目标view,有的话就跳出循环
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
// Dispatch to touch targets.
//没有找到目标view,那么就是执行本身的
if (mFirstTouchTarget == null) {
// No touch targets so treat this as an ordinary view.
//没有找到目标View的时候,调用dispatchTransformedTouchEvent其实会走super.dispatchTouchEvent,因为ViewGroup实际上是继承View的,那么又会走以前分析的View dispatchTouchEvent流程,最终会走到onTouchEvent
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {
final TouchTarget next = target.next;
//alreadyDispatchedToNewTouchTarget=true的话表示上面的view已经消费了该事件
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {
handled = true;
} else {
//继续对子view进行事件分发
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
if (!handled && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(ev, 1);
}
return handled;
}
复制代码
'''