Android中使用RecyclerView实现下拉刷新和上拉加载

2019-12-10 18:50:17于丽

RecyclerView 是Android L版本中新添加的一个用来取代ListView的SDK,它的灵活性与可替代性比listview更好。本文给大家介绍如何为RecyclerView添加下拉刷新和上拉加载,过去在ListView当中添加下拉刷新和上拉加载是非常方便的利用addHeaderView和addFooterView,RecyclerView的刷新同样也是需要靠List当中添加Head或Foot来实现的。本篇不会详细告诉你怎么去做一个下拉刷新和加载的效果,而是如何快速利用现有的知名开源库来为RecyclerView实现下面的效果。

先给大家展示下效果图,感兴趣的朋友请继续阅读全文。

Android,RecyclerView,下拉刷新,上拉加载

这个下拉刷新不是靠List当中添加HeaderView来实现的,而是在RecyclerView外面套了一层ViewGroup而这个ViewGroup支持下拉刷新,可以灵巧的实现一些子View的下拉刷新,这个就是大名鼎鼎的android-Ultra-Pull-To-Refresh开源库,作者liaohuqiu,但是很遗憾它不支持上拉加载,本篇用的是在这个库基础上进行了拓展并实现了上拉加载效果的开源库,上拉的效果实现是靠RecyclerView里添加FooterView,Github地址:https://www.easck.com/p>

//可选 或者在上面地址中下载library源代码copy到项目里面
compile 'com.chanven.lib:cptr:1.0.0' 
// RecyclerView和CardView
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:cardview-v7:23.1.1'

2:主布局文件 activity_main.xml 里面一个RecyclerView 外面嵌套的是支持下拉刷新的ViewGroup

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.chanven.lib.cptr.PtrClassicFrameLayout
android:id="@+id/rotate_header_list_view_frame"
xmlns:cube_ptr="http://www.easck.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e1e1e1"
cube_ptr:ptr_duration_to_close="200"
cube_ptr:ptr_duration_to_close_header="1000"
cube_ptr:ptr_keep_header_when_refresh="true"
cube_ptr:ptr_pull_to_fresh="false"
cube_ptr:ptr_ratio_of_header_height_to_refresh="1.2"
cube_ptr:ptr_resistance="1.7">
<android.support.v7.widget.RecyclerView
android:background="#ffffff"
xmlns:android="http://www.easck.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/rv_list"
/>
</com.chanven.lib.cptr.PtrClassicFrameLayout>
</LinearLayout>