一、RecyclerView下拉刷新
这里直接使用google提供的support-v4包种的SwipeRefreshLayout
1、在布局中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.raphets.recyclerview.MainActivity" >
<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>
</RelativeLayout>
2、在MainActivity中,给SwipeRefreshLayout设置监听
mRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
// 下拉刷新
mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh() {
mDatas.clear();
for (int i = 0; i <= 50; i++) {
mDatas.add("item---" + new Random().nextInt(30));
}
adapter.notifyDataSetChanged();
mRefreshLayout.setRefreshing(false);
}
});
二、RecylcerView上拉自动加载
这里我们通过重写RecyclerView的OnScrollListener方法,实现上拉加载
// 上拉自动加载
mRecyclerView.setOnScrollListener(new OnScrollListener() {
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
int last = manager.findLastCompletelyVisibleItemPosition();
int totalCount = manager.getItemCount();
// last >= totalCount - 2表示剩余2个item是自动加载,可自己设置
// dy>0表示向下滑动
if (last >= totalCount - 2 && dy > 0) {
/*
* 加载数据
*/
List<String> datas = new ArrayList<String>();
for (int i = 0; i <= 10; i++) {
datas.add("load" + new Random().nextInt(10));
}
//addData()是在自定义的Adapter中自己添加的方法,用来给list添加数据
adapter.addData(datas);
}
}
});
其中自定义的Adapter中自己添加的方法代码:
//添加数据集合
public void addData(List<String> datas) {
mDatas.addAll(datas);
notifyDataSetChanged();
}