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();
}
}
}