Skip to content

Instantly share code, notes, and snippets.

@vuhung3990
Last active August 14, 2017 06:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
recycleview load more helper
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();
}
}
}
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");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment