-
-
Save zahid371919/b631bad2954c9a86e1b9ceb95d7e7b18 to your computer and use it in GitHub Desktop.
RecyclerView Auto Scroll Loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment