RecyclerView 的下拉刷新与上拉加载更多

阅读 4209
收藏 91
2017-02-04
原文链接:www.jianshu.com

下拉刷新上拉加载更多,从设计层面上来说,就不是同一个层面上的,从Google官方推出的下拉刷新控件SwipeRefreshLayout就可以看出。
一般来说,下拉刷新是以包裹整个列表控件的容器来实现的,而上拉加载更多是以列表控件的一部分扩展(footerView)来实现的。

下拉刷新

  1. Google官方的SwipeRefreshLayout
    xml中控件初始化:

    <android.support.v4.widget.SwipeRefreshLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">
    
       <android.support.v7.widget.RecyclerView
           android:id="@+id/recyclerView"
           android:layout_width="match_parent"
           android:layout_height="match_parent"/>
    
    </android.support.v4.widget.SwipeRefreshLayout>

    java类中实现

         // 设置下拉出现小圆圈是否是缩放出现,出现的位置,最大的下拉位置
         mySwipeRefreshLayout.setProgressViewOffset(true, 50, 200);
    
         // 设置下拉圆圈的大小,两个值 LARGE, DEFAULT
         mySwipeRefreshLayout.setSize(SwipeRefreshLayout.LARGE);
    
         // 设置下拉圆圈上的颜色,蓝色、绿色、橙色、红色
         mySwipeRefreshLayout.setColorSchemeResources(
                 android.R.color.holo_blue_bright,
                 android.R.color.holo_green_light,
                 android.R.color.holo_orange_light,
                 android.R.color.holo_red_light);
    
         // 通过 setEnabled(false) 禁用下拉刷新
         mySwipeRefreshLayout.setEnabled(false);
    
         // 设定下拉圆圈的背景
         mSwipeLayout.setProgressBackgroundColor(R.color.red);
    
         /*
          * 设置手势下拉刷新的监听
          */
         mySwipeRefreshLayout.setOnRefreshListener(
                 new SwipeRefreshLayout.OnRefreshListener() {
                     @Override
                     public void onRefresh() {
                         // 刷新动画开始后回调到此方法
                     }
                 }
         );
  2. 使用第三方下拉刷新控件,可以更好地支持自定义下拉样式。
    这里推荐一个比较好的第三方控件:android-Ultra-Pull-To-Refresh

    compile 'in.srain.cube:ultra-ptr:1.0.10'

    xml中控件初始化:

     <in.srain.cube.views.ptr.PtrFrameLayout
         xmlns:app="http://schemas.android.com/apk/res-auto"
         android:id="@+id/refreshView"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         app:ptr_duration_to_close="200"
         app:ptr_duration_to_close_header="1000"
         app:ptr_keep_header_when_refresh="true"
         app:ptr_pull_to_fresh="false"
         app:ptr_ratio_of_header_height_to_refresh="1.2"
         app:ptr_resistance="1.7">
    
         <com.zdf.zhihu.view.widget.LoadMoreRecyclerView
             android:id="@+id/recyclerView"
             android:layout_width="match_parent"
             android:layout_height="wrap_content">
    
         </com.zdf.zhihu.view.widget.LoadMoreRecyclerView>
    
     </in.srain.cube.views.ptr.PtrFrameLayout>

    java类中实现:

     private void initRefreshView() {
         // 这里可以完全自定义各种样式,只要实现PtrUIHandler,
         // 具体请参考官方文档也源码
         MaterialHeader header = new MaterialHeader(getContext());
         refreshView.setHeaderView(header);
         refreshView.addPtrUIHandler(header);
         refreshView.setPtrHandler(new PtrDefaultHandler() {
             @Override
             public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                 page = 0;
                 requestTopMovies();
             }
         });
     }
    
     @Override
     public void autoRefresh() {
         handler.postDelayed(new Runnable() {
             @Override
             public void run() {
                 refreshView.autoRefresh();
             }
         }, 100);
     }
    
     @Override
     public void refreshComplete() {
         handler.post(new Runnable() {
             @Override
             public void run() {
                 refreshView.refreshComplete();
             }
         });
     }

上拉加载更多

以列表控件的一部分扩展实现,这里以RecyclerView为例,新建一个类LoadMoreRecyclerView,继承至RecyclerView,主要的功能就是实现加载更多逻辑和显示控件:

/**
 * 集成了上拉加载更多的RecyclerView
 *
 * Created by XiaoFeng on 2017/2/3.
 */
public class LoadMoreRecyclerView extends RecyclerView {

    private final int STATE_NONE = 0x00;
    private final int STATE_LOADING = 0x01;
    private final int STATE_FAILURE = 0x02;
    private final int STATE_COMPLETE = 0x03;

    // 滑到底部里最后一个个数的阀值
    private static final int VISIBLE_THRESHOLD = 1;

    private int state;
    private boolean loadMoreEnabled = true;
    private OnLoadMoreListener listener;
    private SuperAdapter superAdapter;
    private LoadMoreView loadMoreView;
    private LinearLayoutManager layoutManager;

    public LoadMoreRecyclerView(Context context) {
        this(context, null);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LoadMoreRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public void initLoadMore(@NonNull OnLoadMoreListener listener) {
        this.listener = listener;

        if (getAdapter() instanceof SuperAdapter) {
            superAdapter = (SuperAdapter) getAdapter();
        }

        loadMoreView = new LoadMoreView(getContext());
        layoutManager = (LinearLayoutManager) getLayoutManager();

        addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                if (canLoadMore() && dy >= 0) {
                    int totalItemCount = layoutManager.getItemCount();
                    int lastVisibleItem = layoutManager.findLastVisibleItemPosition();
                    if (lastVisibleItem + VISIBLE_THRESHOLD >= totalItemCount) {
                        onLoadMore(recyclerView);
                    }
                }
            }
        });
    }

    public void setLoadMoreEnabled(boolean enabled) {
        this.loadMoreEnabled = enabled;
    }

    private boolean canLoadMore() {
        return state != STATE_LOADING && loadMoreEnabled;
    }

    private void onLoadMore(RecyclerView recyclerView) {
        state = STATE_LOADING;

        if (loadMoreView != null) {
            loadMoreView.loading();
        }

        recyclerView.post(new Runnable() {
            @Override
            public void run() {
                if (state == STATE_LOADING) {
                    if (superAdapter != null && loadMoreView != null) {
                        superAdapter.addFooterView(loadMoreView);
                    }
                }
            }
        });

        if (listener != null) {
            listener.onLoadMore();
        }
    }

    public void loadMoreFailed() {
        state = STATE_FAILURE;

        if (loadMoreView != null) {
            loadMoreView.failure();
        }

        if (superAdapter != null) {
            superAdapter.removeFooterView();
        }
    }

    public void loadMoreComplete() {
        state = STATE_COMPLETE;

        if (loadMoreView != null) {
            loadMoreView.complete();
        }

        if (superAdapter != null) {
            superAdapter.removeFooterView();
        }
    }
}

上面出现的SuperAdapter是使用了一个第三方封装的万能Adapter,同时支持ListView和RecyclerView,个人感觉比鸿洋大神封装的万能Adapter要好一些,但是基本原理都是一样的。原理可以看他们各自的文章介绍,已经写的很详细了,这里就不多说了。

www.jianshu.com/p/d6a76fd3e…
blog.csdn.net/lmj62356579…
blog.csdn.net/lmj62356579…

关于分页加载

伴随着上拉加载更多功能的,往往是分页加载,关于分页加载的页数是在列表控件内部自动控制?还是在列表控件外部自己控制?我个人认为应该放在列表控件外部自己来控制页数,因为这个页数不光是在上拉加载更多时会使用到,在下拉刷新的时候也会使用到,并且对页数需要清零。
这里提供一种在列表控件外部控制页数的实现逻辑:

    // 分页页数
    private int page = 0;

    // 初始化下拉刷新控件
    private void initRefreshView() {
        MaterialHeader header = new MaterialHeader(getContext());
        refreshView.setHeaderView(header);
        refreshView.addPtrUIHandler(header);
        refreshView.setPtrHandler(new PtrDefaultHandler() {
            @Override
            public void onRefreshBegin(PtrFrameLayout ptrFrameLayout) {
                page = 0;
                requestTopMovies();
            }
        });
    }

    // 初始化RecyclerView,包含上拉加载更多
    private void initRecyclerView() {
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new SubjectAdapter(getContext());
        recyclerView.setAdapter(adapter);
        recyclerView.initLoadMore(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                page++;
                requestTopMovies();
            }
        });
    }

    // 具有分页操作的网络请求
    private void requestTopMovies() {
        Subscriber subscriber = new RxCallback<List<Movie>>() {
            @Override
            public void onSuccess(List<Movie> movieList) {
                if (adapter != null) {
                    if (page == 0) {
                        adapter.clear();
                    } else {
                        recyclerView.loadMoreComplete();
                    }
                    adapter.addAll(movieList);
                }
            }

            @Override
            public void onFinished() {
                refreshComplete();
            }
        };
        RxRetrofitClient.getInstance().requestTop250Movies(subscriber, page, 10);
    }

参考:
github.com/hanks-zyh/S…
www.jianshu.com/p/d6a76fd3e…
blog.csdn.net/lmj62356579…
blog.csdn.net/lmj62356579…

评论