[Android开发艺术探索阅读笔记]第3章 View的事件体系

本章将介绍Android中十分重要的一个概念:View,虽然说View不属于四大组件,但是它的作用堪比四大组件,甚至比Receiver和Provider的重要性都要大。在Android开发中,Activity承担这可视化的功能,同时Android系统提供了很多基础控件,常见的有Button、TextView、CheckBox等。很多时候仅仅使用系统提供的控件是不能满足需求的,因此我们就需要能够根据需求进行新控件的定义,而控件的自定义就需要对Android的View体系有深入的理解,只有这样才能写出完美的自定义控件。

View的基础知识

主要介绍内容:

  1. View的位置参数
  2. MotionEvent 和 TouchSlop对象
  3. VelocityTracker
  4. GestureDetector
  5. Scroller

View 的位置参数

主要由四个顶点来决定:

  1. top:左上角纵坐标
  2. left:左上角横坐标
  3. right:右下角横坐标
  4. bottom:右下角纵坐标

四个顶点坐标都是相对于View的父容器来说的。是相对坐标。

View 的宽高和坐标的关系:

width = right - left;
height = bottom - top
复制代码

在View的源码中四个坐标对应于mLeft,mRight,mTop,mBottom这四个成员变量。View中有对应的方法获取这四个值:

mleft = getLeft();
mRight = getRight();
mTop = getTop();
mBottom = getBottom();
复制代码

从Android 3.0 之后,View增加了额外的几个参数:

  1. (x, y): View左上角的坐标
  2. translationX: View左上角相对于父容器X方向的偏移量,默认值为0
  3. translationY: View左上角相对于父容器Y方向的偏移量,默认值为0

View中提供了对应的Get/Set方法。

public float getX() {
    return mLeft + getTranslationX();
}

public void setX(float x) {
    setTranslationX(x - mLeft);
}

public float getY() {
    return mTop + getTranslationY();
}

public void setY(float y) {
    setTranslationY(y - mTop);
}



复制代码

x = left + translationX
y = top + translationY

注意: View在平移的过程中,top和left表示的是原始左上角的位置信息,其值并不会发生改变。发生变化的是x,y,translationX,translationY。

MotionEvent和TouchSlop

MotionEvent

手指接触屏幕后会产生一些列事件。典型的有下面几种:

  1. ACTION_DOWN: 手指刚接触屏幕
  2. ACTION_MOVE: 手指在屏幕上滑动
  3. ACTION_UP: 手指从屏幕上松开的一瞬间

2种时间序列:

  1. 点击屏幕立刻松开, 事件序列为: DOWN->UP
  2. 点击屏幕后滑动一会再松开,事件序列为:DOWN->MOVE...->UP

通过MotionEvent可以得到点击事件发生的坐标(x,y)。

getX/getY: 得到相对于View左上角的坐标(x,y) getRawX/getRawY:得到相对于手机屏幕的坐标(x,y)

TouchSlop

TouchSlop是系统所能识别出的被认为是滑动的最小距离。

这是一个常量,不同设备值可能不一样。

获取方式:ViewConfiguration.get(getCon-text()).getScaledTouchSlop()。

可以利用这个常量做一些滑动的过滤。

在源码中可以找到这个常量的定义:frameworks/base/core/ res/res/values/config.xml

<!--Base "touch slop" value used by ViewConfiguration as a movement threshold     where scrolling should begin. -->   
<dimen name="config_viewConfigurationTouchSlop">8dp</dimen>
复制代码

VelocityTracker、GestureDetector和Scroller

VelocityTracker

追踪手指在滑动过程中的速度。包括水平和竖直

VelocityTracker velocityTracker = VelocityTracker.obtain();
// 1000代表速度的单位为1秒
velocityTracker.computeCurrentVelocity(1000);
float xVelocity = velocityTracker.getXVelocity();
float yVelocity = velocityTracker.getYVelocity();
复制代码
  1. 获取速度之前先计算速度。先调用computeCurrentVelocity
  2. 这里的速度是指一段时间手指划过的像素数。

不使用的时候需要调用recyle回收内存。

velocityTracker.recycle();
复制代码
GestureDetector

手势检测,用于辅助检测用户的单击,滑动,长按,双击等行为。

    // 创建GestureDetector对象
    GestureDetector gestureDetector = new GestureDetector(getContext(), mOnGestureListener);
    // 设置长按屏幕后可以拖动
    gestureDetector.setIsLongpressEnabled(false);

    // 接管事件
    boolean b = gestureDetector.onTouchEvent(event);
复制代码

OnGestureListener和OnDoubleTapListener中的方法介绍:

实际开发中,如果只是监听滑动相关的,建议在onTouchEvent中实现。如果要监听双击行为就使用GestureDetector。

Scroller

用于实现View的弹性滑动。

Scroller 让View在一定时间内完成连续的滑动。Scrller本身无法让View弹性滑动,需要和View的computeScroll方法配合使用才能共同使用。

Scroller只能是父View使用,来滑动子View。

public class ViewA extends LinearLayout {
  private Scroller mScroller;

  public ViewA(Context context) {
    super(context);
    init(context);
  }

  public ViewA(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
    init(context);
  }

  public ViewA(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init(context);
  }

  @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
  public ViewA(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init(context);
  }

  private void init(Context context) {
    mScroller = new Scroller(context);
  }

  public void smoothScrollTo(int destX, int destY) {
    int scrollX = getScrollX();
    int scrollY = getScrollY();
    int deltaX = destX - scrollX;
    int deltaY = destY - scrollY;
    // (scrollX,scrollY) 是view左上角的初始坐标。dx,dy是位移量,x正数左移动。y正数上移动
    mScroller.startScroll(scrollX, scrollY, -deltaX, -deltaY, 1000);

    invalidate();
  }

  @Override public void computeScroll() {
    super.computeScroll();
    if (mScroller.computeScrollOffset()) {
      scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
      postInvalidate();
    }
  }
}

复制代码

View 的滑动

通过三种方式可以实现View的滑动:

  1. 第一种是通过View本身提供的scrollTo/scrollBy方法来实现滑动;
  2. 第二种是通过动画给View施加平移效果来实现滑动;
  3. 第三种是通过改变View的LayoutParams使得View重新布局从而实现滑动。

使用scrollTo/scrollBy

    /**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;
            mScrollY = y;
            invalidateParentCaches();
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            if (!awakenScrollBars()) {
                postInvalidateOnAnimation();
            }
        }
    }
    
    
    /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }
复制代码

mScrollX 和 mScrollY 的改变规则:

在滑动的过程中,mScrollX 的值总是等于View左边缘和View内容左边缘的水平距离。mScrollY的值总是等于View上边缘和View内容上边缘在竖直方向的距离。

设原来View左上角的坐标为(a,b),移动后View内容的左上角坐标为(a',b'),则:

mScrollX = a - a'
mScrollY = b - b'
复制代码

如果mScrollX>0,View的内容往左边移动了。反之右移了。
如果mScrollY>0,View的内容往上移动了,反之就下移了。

mScrollX和mScrollY的变换规律示意:

只能改变View内容的位置而不能改变view在布局中的位置。

使用动画

使用属性动画。

改变布局参数

  1. 改变LayoutParams。比如右移一个view 10dp,只需要设置它的marginLeft为10dp。
  2. 放置一个宽度为0的空view,当我们需要向右移动Button时,只需要重新设置空View的宽度即可,当空View的宽度增大时(假设Button的父容器是水平方向的LinearLayout),Button就自动被挤向右边,即实现了向右平移的效果。

各种滑动方式对比

scrollTo/scrollBy 只能滑动View的内容,不能滑动View本身。

动画只能3.0以上使用属性动画,3.0以下使用View动画不能改变本身的属性,动画有一个优点,它可以实现比较复杂的效果。

  • scrollTo/scrollBy:操作简单,适合对View内容的滑动;
  • 动画:操作简单,主要适用于没有交互的View和实现复杂的动画效果;
  • 改变布局参数:操作稍微复杂,适用于有交互的View。

跟手滑动的例子

实现一个跟手滑动的效果,这是一个自定义View,拖动它可以让它在整个屏幕上随意滑动。

实现View的onTouchEvent方法在里面处理ACTION_MOVE事件。

 @Override public boolean onTouchEvent(MotionEvent event) {
    float rawX = event.getRawX();
    float rawY = event.getRawY();
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        break;
      case MotionEvent.ACTION_MOVE:
        float deltaX = rawX - mLastX;
        float deltaY = rawY - mLastY;

        // 移动后的位移改变量
        float translationX = getTranslationX() + deltaX;
        float translationY = getTranslationY() + deltaY;
        // setTranslationX setTranslationY, 改变translationX,Y 的值来改变View的位置
        setTranslationX(translationX);
        setTranslationY(translationY);

        Log.d(TAG,"move,deltaX:" + deltaX + " deltaY:" + deltaY);
        break;
      case MotionEvent.ACTION_UP:
        break;
      default:
        break;
    }

    mLastX = rawX;
    mLastY = rawY;
    return true;
  }
复制代码

弹性滑动

主要思想:将一个大的滑动分成很多个小的滑动。实现方式有多种:

  1. Scroller
  2. Handler#PostDelayed
  3. Thread#sleep

Scroller

当调用Scroller#startScroll()时,内部只是对一些变量进行赋值。

  • startX 滑动的起点x坐标
  • startY 滑动的起点y坐标
  • dx 滑动的x方向距离。正数View就往左移动,负数往右移动
  • dy 滑动的y方向距离。正数View就往上移动,负数往下移动
   public void startScroll(int startX, int startY, int dx, int dy, int duration) {
        mMode = SCROLL_MODE;
        mFinished = false;
        mDuration = duration;
        mStartTime = AnimationUtils.currentAnimationTimeMillis();
        mStartX = startX;
        mStartY = startY;
        mFinalX = startX + dx;
        mFinalY = startY + dy;
        mDeltaX = dx;
        mDeltaY = dy;
        mDurationReciprocal = 1.0f / (float) mDuration;
    }
复制代码
public void smoothScrollTo(int destX, int destY) {
    int scrollX = getScrollX();
    int scrollY = getScrollY();
    int deltaX = destX - scrollX;
    int deltaY = destY - scrollY;
    // (scrollX,scrollY) 是view左上角的初始坐标。dx,dy是位移量,x正数左移动。y正数上移动
    mScroller.startScroll(scrollX, scrollY, -deltaX, -deltaY, 1000);
    invalidate();
  }

  @Override public void computeScroll() {
    super.computeScroll();
    if (mScroller.computeScrollOffset()) {
      scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
      postInvalidate();
    }
  }
复制代码

只调用startScroll方法无法完成滑动,因为他只是赋值而已。在调用startScroll后需要调用invalidate()重绘。父布局会调用View#draw(Canvas canvas, ViewGroup parent, long drawingTime)这个方法中会调用View#computeScroll();

复写computeScroll(),computeScrollOffset()返回true代表滑动还未结束,就需要用scrollTo滑动View。然后调用 postInvalidate()继续重绘,这样形成一个递归,直到computeScrollOffset()返回false代表滑动完成。

    /**
     * Call this when you want to know the new location.  If it returns true,
     * the animation is not yet finished.
     */ 
    public boolean computeScrollOffset() {
        if (mFinished) {
            // 滑动完成直接返回false。
            return false;
        }

        // 已经滑动的时间
        int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
        
        // 如果小于mDuration代表还在滑动
        if (timePassed < mDuration) {
            // 判断2种滑动模式
            switch (mMode) {
            case SCROLL_MODE:
                final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);
                mCurrX = mStartX + Math.round(x * mDeltaX);
                mCurrY = mStartY + Math.round(x * mDeltaY);
                break;
            case FLING_MODE:
                final float t = (float) timePassed / mDuration;
                final int index = (int) (NB_SAMPLES * t);
                float distanceCoef = 1.f;
                float velocityCoef = 0.f;
                if (index < NB_SAMPLES) {
                    final float t_inf = (float) index / NB_SAMPLES;
                    final float t_sup = (float) (index + 1) / NB_SAMPLES;
                    final float d_inf = SPLINE_POSITION[index];
                    final float d_sup = SPLINE_POSITION[index + 1];
                    velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);
                    distanceCoef = d_inf + (t - t_inf) * velocityCoef;
                }

                mCurrVelocity = velocityCoef * mDistance / mDuration * 1000.0f;
                
                mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX));
                // Pin to mMinX <= mCurrX <= mMaxX
                mCurrX = Math.min(mCurrX, mMaxX);
                mCurrX = Math.max(mCurrX, mMinX);
                
                mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));
                // Pin to mMinY <= mCurrY <= mMaxY
                mCurrY = Math.min(mCurrY, mMaxY);
                mCurrY = Math.max(mCurrY, mMinY);

                if (mCurrX == mFinalX && mCurrY == mFinalY) {
                    mFinished = true;
                }

                break;
            }
        }
        else {
            mCurrX = mFinalX;
            mCurrY = mFinalY;
            mFinished = true;
        }
        return true;
    }
复制代码

动画

延迟策略

View的事件分发机制

3个重要的方法:

  // 进行事件的分发,如果事件能够传递给当前的view,此方法一定会被调用。返回的boolean值受到当前View的
  // onTouchEvent()和下级view的dispatchTouchEvent()的影响,true表示消费了事件,false表示不消费。
  @Override public boolean dispatchTouchEvent(MotionEvent ev) {
    return super.dispatchTouchEvent(ev);
  }

  // 在dispatchTouchEvent()中被调用。用来判断是否拦截事件,如果拦截了,同一事件序列不会再调用此方法。
  // 返回true为拦截该事件,false为不拦截。
  @Override public boolean onInterceptTouchEvent(MotionEvent ev) {
    return super.onInterceptTouchEvent(ev);
  }

  // 在dispatchTouchEvent()中被调用。用来处理点击事件,返回true为消费当前事件,false为不消费。如果不
  // 消费,在同一事件序列中,该View无法再次收到事件。
  @Override public boolean onTouchEvent(MotionEvent event) {
    return super.onTouchEvent(event);
  }
复制代码

伪代码:

// 点击事件产生后首先会传递给根ViewGroup,它的dispatchTouchEvent()被调用
public boolean dispatchTouchEvent(MotionEvent ev) {
    boolean consume = false;
    // 如果它拦截了事件,由onTouchEvent()来处理是否消费,否则交给子类。
    if (onInterceptTouchEvent(ev)) {
        consume = onTouchEvent(ev);
    } else {
        consume = child.dispatchTouchEvent(ev);
    }
    return consume;
}
复制代码

onTouchListener

    /**
     * Interface definition for a callback to be invoked when a touch event is
     * dispatched to this view. The callback will be invoked before the touch
     * event is given to the view.
     */
    public interface OnTouchListener {
        /**
         * Called when a touch event is dispatched to a view. This allows listeners to
         * get a chance to respond before the target view.
         *
         * @param v The view the touch event has been dispatched to.
         * @param event The MotionEvent object containing full information about
         *        the event.
         * @return True if the listener has consumed the event, false otherwise.
         */
        boolean onTouch(View v, MotionEvent event);
    }
复制代码

如果一个View设置了onTouchListenr,那么onTouchListenr的onTouch方法会被回调。返回true表示onTouchListenr消耗了这个事件,onTouchEvent()不会被调用。
在onTouchEvent方法中,如果view设置了OnClickListenr, 那么onClik()方法会被回调。

优先级:OnTouchListener > onTouchEvent > OnClickListener

事件传递过程

Activity -> Window -> View。
顶级View接收到事件后就会按照事件分发机制去分发事件。

如果一个View的onTouchEvent返回false,那么它的父容器的onTouchEvent()会被执行。依次类推,都不处理的话最后会返回到Activity的onTouchEvent()处理。

Activity#onTouchEvent(MotionEvent event)

    /**
     * Called when a touch screen event was not handled by any of the views
     * under it.  This is most useful to process touch events that happen
     * outside of your window bounds, where there is no view to receive it.
     *
     * @param event The touch screen event being processed.
     *
     * @return Return true if you have consumed the event, false if you haven't.
     * The default implementation always returns false.
     */
    public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }
复制代码

一些结论

  1. 同一个事件序列是指从手指接触屏幕的那一刻起,到手指离开屏幕的那一刻结束,在这个过程中所产生的一系列事件,这个事件序列以down事件开始,中间含有数量不定的move事件,最终以up事件结束。
  2. 正常情况下,一个事件序列只能被一个View拦截且消耗。这一条的原因可以参考(3),因为一旦一个元素拦截了某此事件,那么同一个事件序列内的所有事件都会直接交给它处理,因此同一个事件序列中的事件不能分别由两个View同时处理,但是通过特殊手段可以做到,比如一个View将本该自己处理的事件通过onTouchEvent强行传递给其他View处理。
  3. 某个View一旦决定拦截,那么这一个事件序列都只能由它来处理(如果事件序列能够传递给它的话),并且它的onIn-terceptTouchEvent不会再被调用。这条也很好理解,就是说当一个View决定拦截一个事件后,那么系统会把同一个事件序列内的其他方法都直接交给它来处理,因此就不用再调用这个View的onInterceptTouchEvent去询问它是否要拦截了。
  4. 某个View一旦开始处理事件,如果它不消耗AC-TION_DOWN事件(onTouchEvent返回了false),那么同一事件序列中的其他事件都不会再交给它来处理,并且事件将重新交由它的父元素去处理,即父元素的onTouchEvent会被调用。意思就是事件一旦交给一个View处理,那么它就必须消耗掉,否则同一事件序列中剩下的事件就不再交给它来处理了,这就好比上级交给程序员一件事,如果这件事没有处理好,短期内上级就不敢再把事情交给这个程序员做了,二者是类似的道理。
  5. 如果View不消耗除ACTION_DOWN以外的其他事件,那么这个点击事件会消失,此时父元素的onTouchEvent并不会被调用,并且当前View可以持续收到后续的事件,最终这些消失的点击事件会传递给Activity处理。
  6. ViewGroup默认不拦截任何事件。Android源码中ViewGroup的onInterceptTouch-Event方法默认返回false。
  7. View没有onInterceptTouchEvent方法,一旦有点击事件传递给它,那么它的onTouchEvent方法就会被调用。
  8. View的onTouchEvent默认都会消耗事件(返回true),除非它是不可点击的(clickable 和longClickable同时为false)。View的longClickable属性默认都为false,clickable属性要分情况,比如Button的clickable属性默认为true,而TextView的clickable属性默认为false。
  9. View的enable属性不影响onTouchEvent的默认返回值。哪怕一个View是disable状态的,只要它的clickable或者longClickable有一个为true,那么它的onTouchEvent就返回true。
  10. onClick会发生的前提是当前View是可点击的,并且它收到了down和up的事件。
  11. 事件传递过程是由外向内的,即事件总是先传递给父元素,然后再由父元素分发给子View,通过requestDisallowIn-terceptTouchEvent方法可以在子元素中干预父元素的事件分发过程,但是ACTION_DOWN事件除外。

源码解析

Activity对点击事件的分发过程

Activty#dispatchTouchEvent(MotionEvent ev)

    /**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        // 如果window处理了就返回true。
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }
复制代码

Window#superDispatchTouchEvent

   /**
     * Used by custom windows, such as Dialog, to pass the touch screen event
     * further down the view hierarchy. Application developers should
     * not need to implement or call this.
     *
     */
    public abstract boolean superDispatchTouchEvent(MotionEvent event);
复制代码

Window是一个抽象类,这个方法也是抽象方法,得去找它的实现类。

/**
 * Abstract base class for a top-level window look and behavior policy.  An
 * instance of this class should be used as the top-level view added to the
 * window manager. It provides standard UI policies such as a background, title
 * area, default key processing, etc.
 *
 * <p>The only existing implementation of this abstract class is
 * android.view.PhoneWindow, which you should instantiate when needing a
 * Window.
 */
复制代码

源码中说明了唯一的实现类就是android.view.PhoneWindow

android.view.PhoneWindow#superDispatchTouchEvent

    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }
    
    // This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;
    
        @Override
    public final View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();
        }
        return mDecor;
    }

复制代码

Window将事件交给了DecorView。

public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks
复制代码

利用 AS 的Layout Inspector 检查Activity的视图:

我们setContentView()就是把View设置在ContentFrameLayout中。


// id为android.R.id.content的View就是 android.support.v7.widget.ContentFrameLayout
View contentView =
        ((ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content)).getChildAt(0);

复制代码

目前事件传到DecorView,由于DecorView继承自FrameLayout,也是也一个View。所以会把事件分发下去。

顶级View的分发
ViewGroup的拦截

ViewGroup#dispatchTouchEvent 检查拦截的逻辑:

// Check for interception.
            final boolean intercepted;
            
             // 满足事件为MotionEvent.ACTION_DOWN或者mFirstTouchTarget不为空时就判断是否需要拦截,
             // 否则直接拦截。DOWN事件之后的就都会拦截,不会走onInterceptTouchEvent方法。
            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);
            }
复制代码

mFirstTouchTarget != null是什么意思?

 // First touch target in the linked list of touch targets.
    private TouchTarget mFirstTouchTarget;  
复制代码

当事件由ViewGroup的子元素成功处理时,mFirstTouchTarget被赋值指向子元素。

当ViewGroup不拦截事件,由子类消费事件时,mFirstTouchTarget != null
当ViewGroup拦截事件,mFristTouchTarget == null

有一种特殊情况:

通过requestDisallowInterceptTouchEvent设置FLAG_DISAL-LOW_INTERCEPT标记位。一般用于子View中。
设置这个标记后,ViewGroup只能拦截ACTION_DOWN事件。如果是ACTION_DOWN就会重置FLAG_DISALLOW_INTERCEPT这个标记位,将导致子View中设置的这个标记位无效。

  // 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();
            }
            
 /**
     * Resets all touch state in preparation for a new cycle.
     */
    private void resetTouchState() {
        clearTouchTargets();
        resetCancelNextUpFlag(this);
        mGroupFlags &= ~FLAG_DISALLOW_INTERCEPT;
        mNestedScrollAxes = SCROLL_AXIS_NONE;
    }            
复制代码

总结:

  1. ViewGroup决定拦截事件后,后续的事件都会交给他处理,不会调用onInterceptTouchEvent()onInterceptTouchEvent不是每次事件都会被调用的,如果我们想提前处理所有的点击事件,要选择dispatchTouchEvent方法,只有这个方法能确保每次都会调用,当然前提是事件能够传递到当前的ViewGroup。
  2. 当子View设置FLAG_DISALLOW_INTERCEPT标记,父View不再拦截事件。FLAG_DISALLOW_INTERCEPT标记位的作用给我们提供了一个思路,当面对滑动冲突时,我们可以是不是考虑用这种方法去解决问题?
ViewGroup不拦截事件时,事件的分发过程
                    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;
                            }
                            
                            // 点击事件的坐标没有落在子元素内或者没有在播放动画,就跳到下一个
                            if (!canViewReceivePointerEvents(child)
                                    || !isTransformedTouchPointInView(x, y, child, null)) {
                                ev.setTargetAccessibilityFocus(false);
                                continue;
                            }

                            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);
                            // 如果子View.dispatchTouchEvent返回true
                            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();
                                
                                //mFirst-TouchTarget就会被赋值同时跳出for循环
                                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();
                    }
复制代码

ViewGroup#dispatchTransformedTouchEvent

if (child == null) {
    // 子类为空就转到View的dispatchTouchEvent
    handled = super.dispatchTouchEvent(event);
} else {
    handled = child.dispatchTouchEvent(event);
}
复制代码
mFirstTouchTarget 的赋值过程

ViewGroup#addTouchTarget

    /**
     * Adds a touch target for specified child to the beginning of the list.
     * Assumes the target child is not already present.
     */
    private TouchTarget addTouchTarget(@NonNull View child, int pointerIdBits) {
        final TouchTarget target = TouchTarget.obtain(child, pointerIdBits);
        // 把新的target插到链表的最前面。
        target.next = mFirstTouchTarget;
        mFirstTouchTarget = target;
        return target;
    }

复制代码

内部是一种单链表结构。

遍历所有的子元素后事件都没有被合适地处理
  1. 第一种是ViewGroup没有子元素;
  2. 第二种是子元素处理了点击事件,但是在dispatchTouchEvent中返回了false,这一般是因为子元素在onTouchEvent中返回了false。
if (mFirstTouchTarget == null) {
    // No touch targets so treat this as an ordinary view.
    handled = dispatchTransformedTouchEvent(ev, canceled, null,
                        TouchTarget.ALL_POINTER_IDS);
}
复制代码
View对点击事件的处理过程
分发dispatchTouchEvent

View#dispatchTouchEvent

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

        boolean result = false;
        
        // .... 
        
        if (onFilterTouchEventForSecurity(event)) {
            if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
                result = true;
            }
            //noinspection SimplifiableIfStatement
            ListenerInfo li = mListenerInfo;
            // 首先判断有没有设置OnTouchListener,
            // 如果mOnTouchListener.onTouch(this, event)返回true,那么onTouchEvent()不会被调用
            if (li != null && li.mOnTouchListener != null
                    && (mViewFlags & ENABLED_MASK) == ENABLED
                    && li.mOnTouchListener.onTouch(this, event)) {
                result = true;
            }

            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }

        // ....
        
        
        // 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;
    }

复制代码

首先会判断有没有设置On-TouchListener,如果OnTouchListener中的onTouch方法返回true,那么onTouchEvent就不会被调用,可见OnTouchListener的优先级高于onTouchEvent,这样做的好处是方便在外界处理点击事件。

onTouchEvent

View#onTouchEvent

   /**
     * Implement this method to handle touch screen motion events.
     * <p>
     * If this method is used to detect click actions, it is recommended that
     * the actions be performed by implementing and calling
     * {@link #performClick()}. This will ensure consistent system behavior,
     * including:
     * <ul>
     * <li>obeying click sound preferences
     * <li>dispatching OnClickListener calls
     * <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
     * accessibility features are enabled
     * </ul>
     *
     * @param event The motion event.
     * @return True if the event was handled, false otherwise.
     */
    public boolean onTouchEvent(MotionEvent event) {
        final float x = event.getX();
        final float y = event.getY();
        final int viewFlags = mViewFlags;
        final int action = event.getAction();
        
        // View不可用时
        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);
        }
        
        // 如果View设置有代理,那么还会执行TouchDelegate的onTouchEvent方法
        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:
                    // ...
                    break;

                case MotionEvent.ACTION_CANCEL:
                    // ...
                    break;

                case MotionEvent.ACTION_MOVE:
                    // ...
                    break;
            }

            return true;
        }

        return false;
    }


复制代码

View#performClick

    /**
     * Call this view's OnClickListener, if it is defined.  Performs all normal
     * actions associated with clicking: reporting accessibility event, playing
     * a sound, etc.
     *
     * @return True there was an assigned OnClickListener that was called, false
     *         otherwise is returned.
     */
    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;
    }
复制代码

只要View的CLICKABLE``和LONG_CLICKABLE或者CONTEXT_CLICKABLE有一个为true,那么它就会消耗这个事件,即onTouchEvent方法返回true,不管它是不是DISABLE状态。UP的时候会执行performClick()在里面调用mOnClickListener回调的onClick方法。

View的LONG_CLICKABLE和CLICKABLE

LONG_CLICKABLE属性默认为false。
而CLICKABLE属性是否为false和具体的View有关。

设置setOnClickListener/setOnLongClickListener时会自动把标记设置为true。

    /**
     * Register a callback to be invoked when this view is clicked. If this view is not
     * clickable, it becomes clickable.
     *
     * @param l The callback that will run
     *
     * @see #setClickable(boolean)
     */
    public void setOnClickListener(@Nullable OnClickListener l) {
        if (!isClickable()) {
            setClickable(true);
        }
        getListenerInfo().mOnClickListener = l;
    }
    
    
    
        /**
     * Register a callback to be invoked when this view is clicked and held. If this view is not
     * long clickable, it becomes long clickable.
     *
     * @param l The callback that will run
     *
     * @see #setLongClickable(boolean)
     */
    public void setOnLongClickListener(@Nullable OnLongClickListener l) {
        if (!isLongClickable()) {
            setLongClickable(true);
        }
        getListenerInfo().mOnLongClickListener = l;
    }
复制代码

View的滑动冲突

常见冲突

  1. 外部滑动方向和内部滑动方向不一致;
  2. 外部滑动方法和内部滑动方向一致
  3. 1和2的嵌套

场景1

ViewPager的内容是ListView, ViewPager内部已经自动做了滑动处理。

如果是ScrollView,就必须手动处理。否则内外两层只有1个能滑动。

还有外部是上下滑动,内部是横向滑动,属于同一类。

场景2

ViewPager中一个左右滑动的ScrollView,我滑动ScrollView不希望切换Viewpager,滑动ScrollView以外的屏幕才切换。

场景3

1 和 2的叠加, 需要分别处理。

处理规则

  • 场景1:
    左右滑动时,让父View拦截点击事件,上下滑动时,让子View拦截事件。 根据滑动的距离,角度,速度等判断是水平滑动还是竖直滑动。

  • 场景2
    比较特殊,比如ScrollView内部有一个ListView,ListView中的内容滑动到顶部和底部时,响应外部ScrollView的滑动,否则就自己处理上下滑动。

  • 场景3
    具体根据业务来决定规则。

解决方式

外部拦截法

所有事件都经过父View来处理,父View需要自己处理就拦截,不需要就分发给子View。需要重写父View的onInterceptTouchEvent,在内部做相应的拦截。 伪代码:

public boolean onInterceptTouchEvent(MotionEvent ev){
    boolean intercepted = false;
    float x = event.getX();
    float y = event.getY();
    switch (ev.getAction()){
        case MotionEvent.ACTION_DOWN:
            // 这里不能拦截,一旦拦截,后续的事件都会被拦截。
            intercepted = false;
            break;
        
        case MotionEvent.ACTION_MOVE:
            if (父容器需要点击事件){
                intercepted = true;
            }else{
                intercepted = false;
            }
            break;
    
        case MotionEvent.ACTION_UP:
            // 必须返回false,给子类处理。
            // 如果返回true,子类无法收到点击事件。
            // 父View如果拦截MOVE事件,后续的事件都会自动拦截。
            intercepted = false;
            break;
        default:
            break;
    }
    
    mLastX = x;
    mLastY = y;
    return intercepted;
}
复制代码
内部拦截法

将所有的事件都分发给子View处理,子View需要就处理,不需要就给父View处理。需要配合requestDisallowInterceptTouchEvent配合使用。 重写子View的dispatchTouchEvent。伪代码:

 @Override public boolean dispatchTouchEvent(MotionEvent event) {
    float x = event.getX();
    float y = event.getY();

    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        // 设置不拦截
        mViewGroup.requestDisallowInterceptTouchEvent(true);
        break;

      case MotionEvent.ACTION_MOVE:
          if (mViewGroup.isNeedEvent()){
            mViewGroup.requestDisallowInterceptTouchEvent(false);
          }

        break;

      case MotionEvent.ACTION_UP:
        break;

      default:
        break;
    }

    mLastX = x;
    mLastY = y;
    return super.dispatchTouchEvent(event);
  }

复制代码

父View需要设置默认拦截除了DOWN事件以外的事件。 ACTION_DOWN事件并不受FLAG_DISALLOW_INTERCEPT这个标记位的控制,所以一旦父容器拦截AC-TION_DOWN事件,那么所有的事件都无法传递到子元素中去。

  @Override public boolean onInterceptTouchEvent(MotionEvent ev) {
    return ev.getAction() != MotionEvent.ACTION_DOWN;
  }
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值