Skip to content

Instantly share code, notes, and snippets.

@walkingError
Created January 18, 2017 13:54
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkingError/8c24e59f969ad9d5c7076d5a2d16db72 to your computer and use it in GitHub Desktop.
Save walkingError/8c24e59f969ad9d5c7076d5a2d16db72 to your computer and use it in GitHub Desktop.
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
/**
* Created by jihoon on 2016. 8. 11..
*/
public abstract class OnScrollEndListener extends RecyclerView.OnScrollListener {
public static int REVERSE = 1;
private boolean isArray;
private boolean reverse;
private StaggeredGridLayoutManager staggeredGridLayoutManager;
private LinearLayoutManager linearLayoutManager;
public OnScrollEndListener(RecyclerView.LayoutManager layoutManager) {
init(layoutManager);
}
public OnScrollEndListener(RecyclerView.LayoutManager layoutManager, int direction) {
this.reverse = direction == REVERSE;
init(layoutManager);
}
private void init(RecyclerView.LayoutManager layoutManager) {
isArray = layoutManager instanceof StaggeredGridLayoutManager;
if (isArray)
staggeredGridLayoutManager = ((StaggeredGridLayoutManager) layoutManager);
else
linearLayoutManager = ((LinearLayoutManager) layoutManager);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
if (isArray) {
int[] positions =
reverse ? staggeredGridLayoutManager.findFirstCompletelyVisibleItemPositions(null)
: staggeredGridLayoutManager.findLastCompletelyVisibleItemPositions(null);
// positions array length equals spancount
int lastPosition = staggeredGridLayoutManager.getItemCount() - 1;
for (int position : positions) {
callbackIfLastPosition(lastPosition, position);
}
} else {
// LinearLayoutManager is super class of GridLayoutManager .
int position =
reverse ? linearLayoutManager.findFirstCompletelyVisibleItemPosition()
: linearLayoutManager.findLastCompletelyVisibleItemPosition();
int lastPosition = linearLayoutManager.getItemCount() - 1; // linearLayoutManager.getItemCount() - 1 - preLoadCount
callbackIfLastPosition(lastPosition, position);
}
}
private void callbackIfLastPosition(int lastPosition, int position) {
if (position == lastPosition) {
loadMore(position);
}
}
public abstract void loadMore(int position);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment