解决NestedScrollView嵌套RecyclerView滑动冲突导致无法正常调用加载更多功能

XML如下:
<android.support.v4.widget.NestedScrollView
    android:id="@+id/nested_scroll_view"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

    <LinearLayout
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.RecyclerView
            android:fadeScrollbars="false"
            android:id="@+id/recycler_view"
            android:layout_height="match_parent"
            android:layout_marginBottom="@dimen/activity_margin_quarter"
            android:layout_marginTop="@dimen/activity_margin_quarter"
            android:layout_width="match_parent"
            android:nestedScrollingEnabled="false"
            android:scrollbars="vertical"
            android:visibility="visible"
            tools:listitem="@layout/item_article_layout" />
    </LinearLayout>
</android.support.v4.widget.NestedScrollView>

  我们可以看到,NestedScrollView 咋看和 ScrollView 的使用很像,都是只有一个childview ----LinearLayout。但是他们并不是继承关系,NestedScrollView是继承的FrameLayout

  在使用NestedScrollView嵌套RecyclerView中,首先会出现的问题就是RecyclerView滑动会出现卡顿,没有惯性滑动的效果。这时只需要调用以下方法就可以了。

recycler_view.setNestedScrollingEnabled(false);

  这个方法主要是设置RecyclerView不处理滚动事件,全部交由ScorllView去处理,这样就解决了滑动卡顿的问题。而一般基于RecyclerView的刷新加载控件都是通过监听滚动事件来判断是否需要执行加载更多操作,这时需要反过来监听ScorllView的滚动事件,判断是否已经滚动到底部了来确定是否需要执行加载更多操作,具体如下:

nestedScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
     
            @Override
            public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
      //scrollY是滑动的距离
                //判断是否滑到的底部
                if (scrollY == (v.getChildAt(0).getMeasuredHeight() - v.getMeasuredHeight())) {
     
                    recyclerView.onLoadMoare();//调用刷新控件对应的加载更多方法
                }
            }
        });

  实现一个OnScrollChangeListener来监听滑动事件,可以获取到滑动的距离,当滑动的距离加上NestedScrollView的高度等于整个LinearLayout的高度时,说明已经滑动到最底部了,那么这时就可以加载更多数据了。如下图:
解决NestedScrollView嵌套RecyclerView滑动冲突导致无法正常调用加载更多功能_第1张图片
参考:NestedScrollView+RecyclerView实现滑动到底部自动加载更新

   解决NestedScrollView嵌套RecyclerView滑动冲突导致无法正常调用加载更多功能

你可能感兴趣的:(#,android)