Android中的事件冲突ScrollView嵌套ListView-----带你轻松入门

在垒代码时总会遇到控件嵌套控件的这种问题,同时也会遇到一些冲突,其中最经典的就是ScrollView嵌套ListView,虽然网上也是提供了大量的解决方案,这些方案在给自己解决问题的同时也带来了宝贵的思路.

废话不多说先给大家来一张图让大家看一下.

这是自己写的一个Demo是有时间冲突的样子

趁着看图的时间大家先思考一个问题

问:ScrollView嵌套ListView为什么会产生冲突

我们先来看看ScrollView的onInterceptTouchEvent(..)

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
    /*
     * This method JUST determines whether we want to intercept the motion.
     * If we return true, onMotionEvent will be called and we do the actual
     * scrolling there.
     */

    /*
    * Shortcut the most recurring case: the user is in the dragging
    * state and he is moving his finger.  We want to intercept this
    * motion.
    */
    final int action = ev.getAction();
     //这个滑动事件没有问题                mIsBeingDragged这个???? 接下来我们看看是什么意思
    if ((action == MotionEvent.ACTION_MOVE) && (mIsBeingDragged)) {
        return true;
    }
//下面的代码忽略不计
}



    /**
     * True if the user is currently dragging this ScrollView around. This is
     * 如果用户当前正在拖动滚动视图,则为True
     * not the same as 'is being flinged', which can be checked by
     * mScroller.isFinished() (flinging begins when the user lifts his finger).
     */
    private boolean mIsBeingDragged = false;

这个mIsBeingDragged是最小滑动像素,只有超过这个值才能滑动,所以在我们滑动的那一瞬间就被拦截,所以Listview不能滑动,

仔细观察我们会发现在MotionEvent.ACTION_MOVE发生前就会产生一个MotionEvent.ACTION_DOWN,所以说在mIsBeingDragged之前事件是没有被拦截的,

既然MotionEvent.ACTION_MOVE没有被拦截我们可以在ListView中接收MotionEvent.ACTION_MOVE和MotionEvent.ACTION_DOWN事件,然后顺着这个思路进行请求ScrollView的拦截事件

接下来看修改后的---------

不足之处请大家点评.....

欢迎访问GitHub:https://github.com/BeaHugs/ScrollViewNestListView

发布了9 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/beahug/article/details/82774974