触摸反馈知识点
1.重写onTouchEvent(),在方法内部定制触摸反馈算法
2.是否消费事件取决于ACTION_DOWN事件或POSITION_DOWN事件是否返回true
3.MotionEvent
1).getActionMasked()和getAction()
2).POINTER_DOWN/POINTER_UP和getActionIndex()
到这里我们通过简单的例子,让读者能够更好的理解上面的知识点
自定义TouchView继承View 重写onTouchEvent方法并返回true
public class TouchView extends View {
public TouchView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "点击TouchView", Toast.LENGTH_SHORT).show();
}
});
点击TouchView这里的toast是没有显示的,接下来我们改下onTouchEvent事件
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getActionMasked() == MotionEvent.ACTION_UP){
performClick();
}
return true;
}
再次点击TouchView 这里的toast就显示出来了,上面的代码其实也很简单就是手势抬起时,调用performClick(),event.getActionMasked()这个方法是根据你不同的手势事件返回不同的事件结果。返回true把事件消费,那什么是消费事件呢?
消费事件
一般流程是子view调用onTouchEvent事件,如果事件没有被消费,那么它会调用它父view的onTouchEvent事件,如果子view消费了事件,也就是返回true,如果你是在按下事件时消费事件,那么它后续的所有事件都不会被执行。同样也不会传递到父view。也就是后续事件均无效。
MotionEvent.ACTION_DOWN
MotionEvent.ACTION_MOVE
MotionEvent.ACTION_UP
MotionEvent.ACTION_CANCEL
MotionEvent.ACTION_POINTER_DOWN
MotionEvent.ACTION_POINTER_UP
event.getAction()与event.getActionMasked()区别
event.getAction()方法是很早就有的,而event.getActionMasked()这个方法是在支持多点触摸的时候出现的,如果你搜索关于触摸反馈相关的文章,可能他们大多是使用event.getAction(),这些文章都是比较老,但这里我推荐读者统一使用event.getActionMasked()
View的onTouchEvent源码解析
获取基本信息
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
view是否可点击
final boolean clickable = ((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE;
CLICKABLE和LONG_CLICKABLE大家应该是比较了解了,这里我就不讲了,我们这里直接看 CONTEXT_CLICKABLE 上下文点击,早期的安卓版本有一个长按菜单,还有就是平板电脑外接蓝牙鼠标,右键点击有一个上下文菜单,也是使用的上下文菜单。
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;
}
不可用状态返回clickable,这个就是如果点击的view被禁用点击事件后后面的事件都不会执行,所以这里代码是直接返回clickable,后面的代码也就不执行操作了。
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
上面这段代码是触摸代理,也就是有可能你触摸的某个view点击范围比较小,可能就没触发点击事件,我们可以使用触摸代理来加大view的点击范围
if (clickable || (viewFlags & TOOLTIP) == TOOLTIP) {
// ....
}
上面的代码比较多,那么我们首先来看下这段条件判断下的代码执行了什么操作,clickable很好理解,TOOLTIP是Android26也就是8.0新增的东西,这里举个简单的例子来了解下TOOLTIP
布局代码如上所示,长按该布局,上面的文字会在你触摸长按事件的上方出现类似吐司的文字,解释当前这个view是什么,也就是解释工具。上面的条件语句也就很好解释了,如果view是可点击,执行条件语句的代码块,如果view不是可点击的,但我这里设置了tooltip,那么条件语句内的代码一样也会执行。
到这里我们就真正的进入到执行具体事件的代码了,我们这里按照时间瞬讯来解读这段源码
首先我们看下MotionEvent.ACTION_DOWN
case MotionEvent.ACTION_DOWN:
//SOURCE_TOUCHSCREEN触摸到屏幕 把手指设置为按下操作
if (event.getSource() == InputDevice.SOURCE_TOUCHSCREEN) {
mPrivateFlags3 |= PFLAG3_FINGER_DOWN;
}
mHasPerformedLongPress = false;
if (!clickable) {
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
break;
}
//检查鼠标右键点击
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);
//检查是否长按,也就是点击不松手,等到了延迟时间还没有松手就触发为长按,所以这里是一个等待的,等待时间为500ms
checkForLongClick(
ViewConfiguration.getLongPressTimeout(),
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
break;
接着分析move
case MotionEvent.ACTION_MOVE:
//按下波纹效果
if (clickable) {
drawableHotspotChanged(x, y);
}
final int motionClassification = event.getClassification();
final boolean ambiguousGesture =
motionClassification == MotionEvent.CLASSIFICATION_AMBIGUOUS_GESTURE;
int touchSlop = mTouchSlop;
if (ambiguousGesture && hasPendingLongPressCallback()) {
final float ambiguousMultiplier =
ViewConfiguration.getAmbiguousGestureMultiplier();
//点击的监听器
if (!pointInView(x, y, touchSlop)) {
// The default action here is to cancel long press. But instead, we
// just extend the timeout here, in case the classification
// stays ambiguous.
removeLongPressCallback();
long delay = (long) (ViewConfiguration.getLongPressTimeout()
* ambiguousMultiplier);
// Subtract the time already spent
delay -= event.getEventTime() - event.getDownTime();
checkForLongClick(
delay,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__LONG_PRESS);
}
touchSlop *= ambiguousMultiplier;
}
// Be lenient about moving outside of buttons
// 事件出去表示结束
if (!pointInView(x, y, touchSlop)) {
// Outside button
// Remove any future long press/tap checks
removeTapCallback();
removeLongPressCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
}
final boolean deepPress =
motionClassification == MotionEvent.CLASSIFICATION_DEEP_PRESS;
if (deepPress && hasPendingLongPressCallback()) {
// process the long click action immediately
removeLongPressCallback();
checkForLongClick(
0 /* send immediately */,
x,
y,
TOUCH_GESTURE_CLASSIFIED__CLASSIFICATION__DEEP_PRESS);
}
break;
case MotionEvent.ACTION_UP:
//手指摸到的置为空
mPrivateFlags3 &= ~PFLAG3_FINGER_DOWN;
if ((viewFlags & TOOLTIP) == TOOLTIP) {
//1.5s后消失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)) {
performClickInternal();
}
}
}
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;
自定义viewGroup 触摸反馈流程
触摸反馈流程
1.Activity.dispatchTouchEvent()
1).递归:ViewGroup(view).dispatchTouchEvent()
(1).ViewGroup.onIntercepterTouchEvent()
(2).child.dispacthTouchEvent()
(3).super.dispatchTouchEvent()
((1)).view.onTouchEvent()
2).Activity.onTouchEvent()
核心原理
对于View,它的DispacthTouchEvent返回的就是它的onTouchEvent
对于ViewGroup的DispatchTouchEvent就要判断它是否被拦截,如果拦截那么他就调用ViewGroup的onTouchEvent,如果没有拦截,则调用ViewGroup的子View的DispacthTouchEvent。
ViewGroup.disPacthTouchEvent
1.如果是用户初次按下(ACTION_DOWN),清空TouchTargets和DISALLOW_INTERCEPT标记
2.拦截处理getParent().requesDisallowIntercepterTouchEvent
3.如果不拦截并且不是CANCEL事件,并且是DOWN或者POINTER_DOWN,尝试把pointer(手势)通过TouchTarget分配给子View:并且如果 分配给了新的子view,调用child.dispatchTouchEvent()把DOWN事件传给子View
4.看有没有TouchTarget
1).如果没有,调用自己的super.dispacthTouchEvent()
2).如果有,调用child.dispatchTouchEvent()把事件传给对应的子View(如果有的话)
5.如果是POINTER_UP,从TouchTargets中清除POINTER信息,如果是UP或CANCEL,重置状态