public abstract class LoadMoreListener extends RecyclerView.OnScrollListener {
//声明一个LinearLayoutManager
private LinearLayoutManager mLinearLayoutManager;
//当前页从0开始
private int currentPage=0;
//已经加载出来的Item的数量
private int totalItemCount;
//主要用来存储上一个totalItemCount
private int preivousTotal=0;
//屏幕上可见的item数量
private int visibleItemCount;
//屏幕上可见的Item中的第一个
private int fistVisibleItem;
//是否正在上拉数据
private boolean loading=true;
public LoadMoreListener(LinearLayoutManager linearLayoutManager) {
mLinearLayoutManager = linearLayoutManager;
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
//屏幕可见的条目数量
visibleItemCount=recyclerView.getChildCount();
//已经加载出来的条目数量
totalItemCount=mLinearLayoutManager.getItemCount();
//屏幕第一个条目可见对应的位置
fistVisibleItem=mLinearLayoutManager.findFirstVisibleItemPosition();
//如果是正在加载数据
if (loading){
if (totalItemCount>preivousTotal){
//说明数据已经加载结束
loading=false;
preivousTotal=totalItemCount;
}
}
if (!loading && totalItemCount-visibleItemCount <= fistVisibleItem){
currentPage++;
onLoadMore(currentPage);
loading=true;
}
}
public abstract void onLoadMore(int currentPage);
}
public class MainActivity extends AppCompatActivity {
private RecyclerView mRv;
private List<String> mList;
private RvAdapter mAdapter;
//数据的总页数
private int totalPager=5;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
initAdapter();
}
private void initView() {
mRv = (RecyclerView) findViewById(R.id.rv);
}
private void initData() {
mList=new ArrayList<>();
for (int i = 0; i < 30; i++) {
mList.add("我是条目:"+i);
}
}
private void initAdapter() {
//初始化适配器
if (mAdapter==null){
mAdapter=new RvAdapter(mList);
}
//ListView形式滑动添加分割线(竖向列表)
LinearLayoutManager mManager=new LinearLayoutManager(this);
mRv.setLayoutManager(mManager);
mRv.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
//条目加载动画
mRv.setItemAnimator(new DefaultItemAnimator());
/**************************加载更多监听******************************/
mRv.addOnScrollListener(new LoadMoreListener(mManager) {
@Override
public void onLoadMore(int currentPage) {
//当前的页数 < 总页数
if (currentPage<totalPager) {
//去加载更多的数据
loadMoreData(currentPage);
}else{
Toast.makeText(MainActivity.this, "大哥没有更多的数据", Toast.LENGTH_SHORT).show();
}
}
});
mRv.setAdapter(mAdapter);
}
private void loadMoreData(int currentPage) {
for (int i = 0; i < 10; i++) {
mList.add("新增条目"+i);
}
mAdapter.notifyDataSetChanged();
}
}