NestedScrollView+RecyclerView实现滑动到底部自动加载更新

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yus201120/article/details/83584560

XML如下:

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

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

                    <android.support.v7.widget.RecyclerView
                        android:id="@+id/recycler_view"
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:layout_marginBottom="@dimen/activity_margin_quarter"
                        android:layout_marginTop="@dimen/activity_margin_quarter"
                        android:fadeScrollbars="false"
                        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。
Java代码:

scrollView.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())){
                    //滑动到底部
                    loadMore();
                }
            }
        });

实现一个OnScrollChangeListener来监听滑动事件,可以获取到滑动的距离,当滑动的距离加上NestedScrollView的高度等于整个LinearLayout的高度时,说明已经滑动到最底部了,那么这时就可以加载更多数据了。如下图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yus201120/article/details/83584560
今日推荐