上拉自动加载的recyclerView

做项目时下拉刷新控件可以直接用google提供,上拉加载更多需要自己实现,在此自己封装了一个recyclerView,根据recyclerView里面的childview数量判断是否继续请求下一页。有一个缺点是上拉加载更多时会多请求一次空数据。

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;

/**
 * @author zhangxiaohui
 * create at 2018/12/29
 */
public class AutoLoadRecyclerView extends RecyclerView {
    private final int PAGE_SIZE = 15, AUTO_LOAD_POS = 5;
    private int repeatLoad = 0;
    private int lastItemCount = PAGE_SIZE + 1;

    public AutoLoadRecyclerView(Context context) {
        super(context);
    }

    public AutoLoadRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public void setOnListner(final AutoLoadMoreListner autoLoadMoreListner) {
        this.addOnScrollListener(new OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState != SCROLL_STATE_IDLE) {//滚动状态不加载
                    return;
                }
                LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    //获取最后一个可见view的位置
                    int lastItemPosition = linearManager.findLastVisibleItemPosition();
                    if (linearManager.getItemCount() == PAGE_SIZE) {//此行重置下拉刷新后可以正常进行分布上拉加载
                        lastItemCount = PAGE_SIZE + 1;
                        repeatLoad = 0;
                    }
                    if (linearManager.getItemCount() < PAGE_SIZE) {//总条数小于一页的数量不再请求下一页
                        return;
                    }
                    //上一次总条数与最新获取的总条数相同不再请求,请求多一次以解决第一页返回PAGE_SIZE数量
                    if ((linearManager.getItemCount() - 1) == lastItemCount && repeatLoad > 1) {
                        return;
                    }
                    repeatLoad++;
                    lastItemCount = lastItemPosition;
                    if (lastItemPosition >= (linearManager.getItemCount() - AUTO_LOAD_POS)) {
                        autoLoadMoreListner.autoLoadMoreData();
                    }
                }
            }
        });
    }

    public interface AutoLoadMoreListner {
        void autoLoadMoreData();
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值