美文网首页
解决ScrollView嵌套RecyclerView的滑动冲突问

解决ScrollView嵌套RecyclerView的滑动冲突问

作者: 我是你森哥哥 | 来源:发表于2018-04-27 09:30 被阅读0次

    1. 自定义ScrollInterceptScrollView继承ScrollView 处理事件的冲突

    public class ScrollInterceptScrollView extends ScrollView {
    private int downX, downY;
    private int mTouchSlop;
    
    public ScrollInterceptScrollView(Context context) {
        this(context, null);
    }
    
    public ScrollInterceptScrollView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }
    
    public ScrollInterceptScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }
    
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ScrollInterceptScrollView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }
    
    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) ev.getRawX();
                downY = (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) ev.getRawY();
                // 判断是否滑动,若滑动就拦截事件
                if (Math.abs(moveY - downY) > mTouchSlop) {
                    return true;
                }
                break;
            default:
                break;
        }
    
        return super.onInterceptTouchEvent(ev);
    }
    }
    

    2. 在布局文件中使用

    正常使用即可 只是需要注意一点 :

    ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆
    RecyclerView 外层必须加上一层RelativeLayout 并且加上这个属性
    android:descendantFocusability="blocksDescendants"
    ☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆

    <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:descendantFocusability="blocksDescendants">
    
                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/rv_content"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:background="@color/bg_White">
    
                    </android.support.v7.widget.RecyclerView>
                </RelativeLayout>
    

    相关文章

      网友评论

          本文标题:解决ScrollView嵌套RecyclerView的滑动冲突问

          本文链接:https://www.haomeiwen.com/subject/hjtblftx.html