Created
January 18, 2017 13:54
-
-
Save walkingError/8c24e59f969ad9d5c7076d5a2d16db72 to your computer and use it in GitHub Desktop.
This file contains 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; | |
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