RecyclerView已经出来很久了,许许多多的项目都开始从ListView转战RecyclerView,那么,上拉加载和下拉刷新是一件很有必要的事情。
在ListView上,我们可以通过自己添加addHeadView和addFootView去添加头布局和底部局实现自定义的上拉和下拉,或者使用一些第三方库来简单的集成,例如Android-pulltorefresh或者android-Ultra-Pull-to-Refresh,后者的自定义更强,但需要自己实现上拉加载。
而在下面我们将用两种方式来实现上拉加载和下拉刷新
第一种方式:SwipeRefreshLayout+滑动底部自动加载
第二种方式:使用第三方库SwipeToLoadLayout实现上拉加载和下拉刷新。
第一种方式:SwipeRefreshLayout+滑动底部自动加载
SwipeRefreshLayout实现很简单,重点是滑动到底部自动加载应该如何实现,其实其实现的方式类似于ListView的实现方式。
看一下activity_recycle_swiperefresh.xml文件:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://www.easck.com/apk/res/android"
android:id="@+id/swipe_refresh"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/swipe_target"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="none" />
</android.support.v4.widget.SwipeRefreshLayout>
布局文件就两个控件,SwipeRefreshLayout中嵌套RecyclerView。
在代码中初始化RecyclerView以及实现adapter等,这不是重点,不再贴代码。
在RecyclerView中有方法addOnScrollListener,该方法类似于ListView的setOnScrollListener方法,OnScrollListener中有两个方法的回调
*onScrolled(RecyclerView recyclerView, int dx, int dy) :滚动的回调,dx和dy表示手指滑动水平和垂直的偏移量。










