scrollview嵌套recyclerview时滑动没有惯性的解决

1、建一个类,继承scrollview,重写里面的方法:

/**
 * 屏蔽 滑动事件
 *
 * Created by 潘洲涛 on 2017/1/1.
*/

class MyScrollview extends ScrollView {
    private int downX;
    private int downY;
    private int mTouchSlop;



    public MyScrollview(Context context) {
        super(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public MyScrollview(Context context, AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    public MyScrollview(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        int action = e.getAction();
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                downX = (int) e.getRawX();
                downY = (int) e.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveY = (int) e.getRawY();
                if (Math.abs(moveY - downY) > mTouchSlop) {
                    return true;
                }
        }
        return super.onInterceptTouchEvent(e);
    }
}


2、在xml文件中引用:

<com.pan.skating.view.MyScrollview
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/act_recycle_super_video_recycleview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</com.pan.skating.view.MyScrollview>

这样就可以了。

在Android中,当ScrollView嵌套RecyclerView,由于两者都是滑动容器,可能会导致滑动冲突,即用户试图向上滚动ScrollView,误触到了RecyclerView滑动,反之亦然。解决这个问题有几种常见方法: 1. **禁止RecyclerView滑动**:在ScrollView内部设置RecyclerView,可以在RecyclerView上添`setOnTouchListener`,并在触摸事件发生检查是否在ScrollView的区域内,如果是,则阻止RecyclerView滑动。例如: ```java recyclerView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { int y = (int) event.getY(); if (!scrollView.canScrollVertically(1) && y > scrollView.getBottom()) { // 防止RecyclerView滑动 return true; } } return false; } }); ``` 2. **使用NestedScrollView替换ScrollView**:在Android API Level 14及以上版本,可以使用NestedScrollView替换ScrollView,它内置了解决滑动冲突的逻辑。 3. **重写RecyclerView的onInterceptTouchEvent**:重写RecyclerView的`onInterceptTouchEvent`方法,在滑动开始判断当前手指的位置是否在ScrollView内,如果不是则让RecyclerView正常滑动。 4. **使用SwipeRefreshLayout**:如果你希望在顶部有一个下拉刷新区域,可以考虑使用SwipeRefreshLayout包裹RecyclerView,这样就可以避免滑动冲突了。 5. **禁用头部或尾部Item的滑动**:针对可能导致冲突的头部或尾部固定布局,可以设置它们不响应触摸事件。 总之,关键在于理解用户意图,并在合适的机切换滑动目标。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值