借鉴自:http://blog.csdn.net/jerrywu145/article/details/52225898
先直接写可以拿去用的东西。
1.下拉刷新 SwipeRefreshLayout
2.上拉加载更多 RecyclerView.OnScrolListener
下拉刷新
布局
<android.support.v4.widget.SwipeRefreshLayout android:id="@+id/swipeRefreshLayout" android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.RecyclerView android:id="@+id/recyclerView" android:layout_width="match_parent" android:layout_height="match_parent" /> </android.support.v4.widget.SwipeRefreshLayout>使用
@BindView(R.id.recyclerView) RecyclerView mRecyclerView; @BindView(R.id.swipeRefreshLayout) SwipeRefreshLayout mSwipeRefreshLayout;
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { //这里写你请求最新数据的操作 } });上拉加载更多
先增加一个类,重写onScrolled方法,直接拷贝即可,不用修改
public abstract class EndlessRecyclerOnScrollListener extends RecyclerView.OnScrollListener { private int previousTotal = 0; private boolean loading = true; int firstVisibleItem, visibleItemCount, totalItemCount; private int currentPage = 1; private LinearLayoutManager mLinearLayoutManager; public EndlessRecyclerOnScrollListener( LinearLayoutManager linearLayoutManager) { this.mLinearLayoutManager = linearLayoutManager; } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); visibleItemCount = recyclerView.getChildCount(); totalItemCount = mLinearLayoutManager.getItemCount(); firstVisibleItem = mLinearLayoutManager.findFirstVisibleItemPosition(); if (loading) { if (totalItemCount > previousTotal) { loading = false; previousTotal = totalItemCount; } } if (!loading && (totalItemCount - visibleItemCount) <= firstVisibleItem) { currentPage++; onLoadMore(currentPage); loading = true; } } public abstract void onLoadMore(int currentPage); }使用
mRecyclerView.addOnScrollListener(new EndlessRecyclerOnScrollListener(linearLayoutManager) { @Override public void onLoadMore(int currentPage) { //这里是你请求历史数据的操作 } });
至于真正的请求数据的业务,我放在了下一篇文章中,下一篇才是重中之重,我会拿开源中国的开源资讯举例,带你了解真实的业务流程。