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

2018-04-27  本文已影响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>
上一篇下一篇

猜你喜欢

热点阅读