yasszu
2/23/2017 - 1:29 AM

RecyclerView Auto Scroll Loader

RecyclerView Auto Scroll Loader

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

public abstract class OnScrollListener extends RecyclerView.OnScrollListener {

    private LinearLayoutManager mLayoutManager;

    private int mVisibleThreshold = 2;
    private int mPreviousItemCount = 0;
    private boolean mLoading = true;

    /**
     * Set this listener to RecyclerView#addOnScrollListener
     *
     * @param mVisibleThreshold is number of remaining items before loading more.
     * @param layoutManager android.support.v7.widget.LinearLayoutManager
     */
    public OnScrollListener(int mVisibleThreshold, LinearLayoutManager layoutManager) {
        this.mVisibleThreshold = mVisibleThreshold;
        this.mLayoutManager = layoutManager;
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        onScrolled();
        int visibleItemCount = mLayoutManager.getChildCount();
        int totalItemCount = mLayoutManager.getItemCount();
        int firstVisibleItems = mLayoutManager.findFirstVisibleItemPosition();
        resetLoadingFrg(totalItemCount);
        loadNextItems(visibleItemCount, totalItemCount, firstVisibleItems);
    }

    public void resetLoadingFrg(int total) {
        if (mLoading && total > mPreviousItemCount){
            mLoading = false;
            mPreviousItemCount = total;
        }
    }

    public void loadNextItems(int visible, int total, int first) {
        if (!mLoading && total <= (first + visible + mVisibleThreshold)) {
            mLoading = true;
            onLoad();
        }
    }

    public void reset() {
        mPreviousItemCount = 0;
        mLoading = true;
    }

    public int getPreviousItemCount() {
        return mPreviousItemCount;
    }

    public abstract void onScrolled();

    public abstract void onLoad();

}