java recycleview加载更多帮手

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java recycleview加载更多帮手相关的知识,希望对你有一定的参考价值。


recycleView = (RecyclerView) findViewById(R.id.recycleview);
recycleView.setHasFixedSize(true);

LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());
layoutManager.setSmoothScrollbarEnabled(true);
recycleView.setLayoutManager(layoutManager);
recycleView.setAdapter(new Adapter());

// threshold = 2 mean if total = 100, scroll to 98 => trigger load more
recycleView.addOnScrollListener(new DetectScrollToEnd(layoutManager, 2) {
    @Override
    protected void onLoadMore() {
        LogUtils.print("load more");
    }
});
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

/**
 * Created by dev22 on 3/1/17.
 * helper class for detect when recyclerView scroll to bottom and load more data
 */
public abstract class DetectScrollToEnd extends RecyclerView.OnScrollListener {
    private final LinearLayoutManager layoutManager;
    private final int mThreshold;
    /**
     * true: scroll down
     */
    private boolean isScrollDown;

    /**
     * trigger when scroll to bottom, depend on threshold number (when have enough item to scroll)
     */
    protected abstract void onLoadMore();

    /**
     * detect scroll to bottom of recycle view
     *
     * @param layoutManager current layout manager
     * @param threshold     should 2 >= threshold < 5
     */
    public DetectScrollToEnd(LinearLayoutManager layoutManager, int threshold) {
        this.layoutManager = layoutManager;
        mThreshold = threshold;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        isScrollDown = dy >= 0;
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        int visibleItemCount = layoutManager.getChildCount();
        int totalItemCount = layoutManager.getItemCount();
        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();

        // scroll end animation and visible item count < total item count (in case total item count not enought to scroll)
        if (newState == RecyclerView.SCROLL_STATE_IDLE && visibleItemCount < totalItemCount) {
            if (isScrollDown && firstVisibleItemPosition + visibleItemCount + mThreshold >= totalItemCount)
                onLoadMore();
        }
    }
}

以上是关于java recycleview加载更多帮手的主要内容,如果未能解决你的问题,请参考以下文章

Android 使用RecycleView列表实现加载更多

滚动时将更多数据加载到recycleview

自己封装的工具类,使用原生SwipeRefreshLayout+RecycleView实现下拉刷新和加载更多

一句代码搞定 RecycleView 侧滑菜单添加头部底部加载更多

嗯嗯,一句代码就搞定 RecycleView 侧滑菜单添加头部底部加载更多

android 卡片画廊效果及RecycleView、ViewPager、ScrollView之前的冲突解决