本文共 17074 字,大约阅读时间需要 56 分钟。
通过导入第三方库实现ListView的上拉加载和下拉刷新比较简单,今天我要讲的是自定义RecyclerView实现下拉刷新和上拉加载。首先,自定义下拉刷新上拉加载是通过给RecyclerView添加头部和尾部实现的。而问题是RecyclerView并没有addHeaderView(View v)和addFooterView(View v)方法。
第一步:自定义HeaderAndFooterWrapper(装饰者模式)实现给RecyclerView添加头部和尾部
方法:public void addHeaderView(View v)
public void addFooterView(View v)
代码参照张鸿洋:Android 优雅的为RecyclerView添加HeaderView和FooterView
链接:
第二步:定义类RefreshRecyclerView并抽取为库
1) 头部布局:refresh_recyclerview_header.xml
<?xml version="1.0" encoding="utf-8"?>
<!--下拉刷新控件-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp">
<ImageView
android:id="@+id/iv_header_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/headview_red_arrow" />
<ProgressBar
android:id="@+id/pb_header_refresh"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:indeterminateDrawable="@drawable/custom_progressbar"
android:visibility="gone" />
</FrameLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:orientation="vertical">
<TextView
android:id="@+id/tv_status"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="下拉刷新"
android:textColor="#ff0000"
android:textSize="18sp" />
<TextView
android:id="@+id/tv_time"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center_horizontal"
android:text="上次更新时间:2016-10-31"
android:textColor="#55000000"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
2)尾部布局(上拉加载部分):refresh_recyclerview_footer.xml
<span style="font-size:14px;"><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:gravity="center"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ProgressBar
android:indeterminateDrawable="@drawable/custom_progressbar"
android:layout_margin="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="加载更多中...."
android:textColor="#ff0000"
android:textSize="25sp"
android:layout_marginLeft="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayou