Android View事件分发机制(1),微信小程序怎么跳转页面

先自我介绍一下,小编浙江大学毕业,去过华为、字节跳动等大厂,目前阿里P7

深知大多数程序员,想要提升技能,往往是自己摸索成长,但自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年最新Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较多,这里只是将部分目录截图出来,全套包含大厂面经、学习笔记、源码讲义、实战项目、大纲路线、讲解视频,并且后续会持续更新

如果你需要这些资料,可以添加V获取:vip204888 (备注Android)
img

正文

// due to an app switch, ANR, or some other state change.

//在开始新的触摸手势时丢弃所有先前的状态。

cancelAndClearTouchTargets(ev);

//重置所有触摸状态以准备新周期。

resetTouchState();

}

//检测拦截

final boolean intercepted;

//事件是按下

if (actionMasked == MotionEvent.ACTION_DOWN || mFirstTouchTarget != null) {

//判断是否禁止拦截 当子View调用requestDisallowInterceptTouchEvent(true)之后,这里的disallowIntercept就是true->禁止拦截 因为子类想接收这个事件并处理自己的逻辑

final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

if (!disallowIntercept) { //子类没有禁止拦截

//是否需要拦截事件 子类可以实现onInterceptTouchEvent()去很轻松的实现事件拦截

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;

}

//检查是否已经被取消了

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;

//如果没被取消 && 没有被拦截

if (!canceled && !intercepted) {

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;

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 preorderedList = buildTouchDispatchChildList();

final boolean customOrder = preorderedList == null && isChildrenDrawingOrderEnabled();

final View[] children = mChildren;

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;

}

// a.如果View不可见并且没有播放动画

// b.点击事件的坐标落在View的范围内

// 满足a或者b则不分发事件给这个view

if (!canViewReceivePointerEvents(child)

|| !isTransformedTouchPointInView(x, y, child, null)) {

ev.setTargetAccessibilityFocus(false);

continue;

}

newTouchTarget = getTouchTarget(child);

if (newTouchTarget != null) {

//子View已经接收触摸事件在自己的范围内,则直接跳出循环,将事件给它自己处理.

// 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的dispatchTouchEvent(event);->子类去分发事件.

//ps: ViewGroup才能分发事件,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();

//将child赋值给mFirstTouchTarget

newTouchTarget = addTouchTarget(child, idBitsToAssign);

alreadyDispatchedToNewTouchTarget = true;

//如果某个child处理了事件,那么就不用继续循环了,直接跳出循环.

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.

if (mFirstTouchTarget == null) {

//没有child接收该事件,则调用super.dispatchTouchEvent(event); 将该事件交给View去处理

// No touch targets so treat this as an ordinary view.

handled = dispatchTransformedTouchEvent(ev, canceled, null, TouchTarget.ALL_POINTER_IDS);

}

return handled;

}

//在ViewGroup中,比View多了一个方法—onInterceptTouchEvent()方法,这个是干嘛用的呢,是用来进行事件拦截的,如果被拦截,事件就不会往下传递了,不拦截则继续。

//子类可以去实现这个方法,然后就可以轻松的拦截事件啦.

public boolean onInterceptTouchEvent(MotionEvent ev) {

if (ev.isFromSource(InputDevice.SOURCE_MOUSE)

&& ev.getAction() == MotionEvent.ACTION_DOWN

&& ev.isButtonPressed(MotionEvent.BUTTON_PRIMARY)

&& isOnScrollbarThumb(ev.getX(), ev.getY())) {

return true;

}

return false;

}

/*

是否能收到事件: 如果可见或者没有播放动画

*/

private static boolean canViewReceivePointerEvents(@NonNull View child) {

return (child.mViewFlags & VISIBILITY_MASK) == VISIBLE

|| child.getAnimation() != null;

}

上面是ViewGroup的分发事件源码,只抽取了源码的部分,关键部分加入了注释.

结论

ViewGroup会遍历所有子View去寻找能够处理点击事件的子View(可见,没有播放动画,点击事件坐标落在子View内部)最终调用子View的dispatchTouchEvent方法处理事件

当子View处理了事件则mFirstTouchTarget 被赋值,并终止子View的遍历。

如果ViewGroup并没有子View或者子View处理了事件,但是子View的dispatchTouchEvent返回了false(一般是子View的onTouchEvent方法返回false)那么ViewGroup会去处理这个事件(本质调用View的dispatchTouchEvent去处理)


下面来看一下View的dispatchTouchEvent()

public boolean dispatchTouchEvent(MotionEvent event) {

boolean result = false;

//如果窗口没有被遮盖

if (onFilterTouchEventForSecurity(event)) {

if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {

result = true;

}

//noinspection SimplifiableIfStatement

//监听事件

ListenerInfo li = mListenerInfo;

//这里的li.mOnTouchListener.onTouch(this, event)是有返回值的,如果是返回了true,那么result就是true了. 相当于处理了触摸事件

if (li != null && li.mOnTouchListener != null

&& (mViewFlags & ENABLED_MASK) == ENABLED

&& li.mOnTouchListener.onTouch(this, event)) {

result = true;

}

//result为false时调用自己的onTouchEvent()去处理该事件.

if (!result && onTouchEvent(event)) {

result = true;

}

}

return result;

}

从上面的代码中可以看出,如果设置了OnTouchListener并且onTouch方法返回了true,那么onTouchEvent不会被调用。

我们来看看onTouchEvent()方法

public boolean onTouchEvent(MotionEvent event) {

final float x = event.getX();

final float y = event.getY();

final int viewFlags = mViewFlags;

final int action = event.getAction();

//CLICKABLE和LONG_CLICKABLE任何一个都可以消费该事件

//TextView默认是clickable是false,Button默认是true

//设置setOnClickListener()时会将clickable置为true

//设置setOnLongClickListener()时会将longClickable置为true

final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE

|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)

|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;

//即使View被设置成了不可用(setEnable(false)->DISABLED),但它还是可以消费点击事件

if ((viewFlags & ENABLED_MASK) == DISABLED) {

if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {

setPressed(false);

}

mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;

// A disabled view that is clickable still consumes the touch

// events, it just doesn’t respond to them.

return clickable;

}

if (mTouchDelegate != null) {

if (mTouchDelegate.onTouchEvent(event)) {

return true;

}

}

if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {

switch (action) {

case MotionEvent.ACTION_UP:

mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;

if ((viewFlags & TOOLTIP) == TOOLTIP) {

handleTooltipUp();

}

if (!clickable) {

removeTapCallback();

removeLongPressCallback();

mInContextButtonPress = false;

mHasPerformedLongPress = false;

mIgnoreNextUpEvent = false;

break;

}

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)) {

//在ACTION_UP 方法发生时,会触发performClick()方法.

performClick();

}

}

}

}

最后

针对Android程序员,我这边给大家整理了一些资料,包括不限于高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter等全方面的Android进阶实践技术;希望能帮助到大家,也节省大家在网上搜索资料的时间来学习,也可以分享动态给身边好友一起学习!

往期Android高级架构资料、源码、笔记、视频。高级UI、性能优化、架构师课程、混合式开发(ReactNative+Weex)全方面的Android进阶实践技术,群内还有技术大牛一起讨论交流解决问题。

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注Android)
img

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

最后

针对Android程序员,我这边给大家整理了一些资料,包括不限于高级UI、性能优化、架构师课程、NDK、混合式开发(ReactNative+Weex)微信小程序、Flutter等全方面的Android进阶实践技术;希望能帮助到大家,也节省大家在网上搜索资料的时间来学习,也可以分享动态给身边好友一起学习!

往期Android高级架构资料、源码、笔记、视频。高级UI、性能优化、架构师课程、混合式开发(ReactNative+Weex)全方面的Android进阶实践技术,群内还有技术大牛一起讨论交流解决问题。

[外链图片转存中…(img-JepeLDee-1713661520828)]

[外链图片转存中…(img-LyfVNSBH-1713661520828)]

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化的资料的朋友,可以添加V获取:vip204888 (备注Android)
[外链图片转存中…(img-wkO7iRAJ-1713661520828)]

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值