recyclerview分页加载,需要重写OnScrollListener。
activity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MainAdapter adapter;
private ProgressBar progressBar;
private int page = 0;
private List<People> peopleList;
private int index = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recyclerView);
progressBar = findViewById(R.id.progressBar);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
adapter = new MainAdapter(this);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new LoadMoreOnScrollListener(linearLayoutManager) {
@Override
public void onLoadMore(int currentPage) {
if (currentPage > page) {
delay();
}
}
});
peopleList = new ArrayList<>();
delay();
}
private void delay() {
progressBar.setVisibility(View.VISIBLE);
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1500);
runOnUiThread(new Runnable() {
@Override
public void run() {
progressBar.setVisibility(View.GONE);
getData();
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
private void getData() {
for (int i=0; i < 30; i++) {
People people = new People();
people.setName("name:" + index);
people.setAge(index);
peopleList.add(people);
index++;
}
page++;
adapter.setData(peopleList);
}
}
核心类LoadMoreOnScrollListener
package com.example.myapplication.listener;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
public abstract class LoadMoreOnScrollListener extends RecyclerView.OnScrollListener {
private LinearLayoutManager mLinearLayoutManager;
private int currentPage = 1;
/**
* 已经加载出来的item个数
*/
private int totalItemCount;
/**
* 上一个totalItemCount
*/
private int previousTotal = 0;
/**
* 屏幕上可见item个数
*/
private int visibleItemCount;
/**
* 屏幕可见item的第一个
*/
private int firstVisiableItem;
/**
* 是否正在上拉数据
*/
private boolean isPulling = true;
public LoadMoreOnScrollListener(LinearLayoutManager linearLayoutManager) {
this.mLinearLayoutManager = linearLayoutManager;
}
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
// 可见item个数
visibleItemCount = recyclerView.getChildCount();
// item总数
totalItemCount = mLinearLayoutManager.getItemCount();
// 第一个可见item
firstVisiableItem = mLinearLayoutManager.findFirstVisibleItemPosition();
if (isPulling) {
if (totalItemCount > previousTotal) {
// 数据成功获取才会执行 说明数据已经加载结束
isPulling = false;
previousTotal = totalItemCount;
}
}
//如果获取数据失败,则不会这行此处,因为loading始终为true
//当最后一个item可见时,执行加载
if (!isPulling && totalItemCount - visibleItemCount <= firstVisiableItem) {
currentPage ++;
onLoadMore(currentPage);
isPulling = true;
}
}
public abstract void onLoadMore(int currentPage);
}