Created
November 27, 2014 15:19
-
-
Save NikolaDespotoski/1a6bb83dbae133f67812 to your computer and use it in GitHub Desktop.
Fix for known bug when scrolling a RecyclerView inside SwipeRefreshLayout to the top and refresh is called prematurely, before the first item is shown.
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
public class SwipeRefreshLayoutToggleScrollListener extends RecyclerView.OnScrollListener { | |
private List<RecyclerView.OnScrollListener> mScrollListeners = new ArrayList<RecyclerView.OnScrollListener>(); | |
private int mExpectedVisiblePosition = 0; | |
private SwipeRefreshLayout mSwipeLayout; | |
public SwipeRefreshLayoutToggleScrollListener(SwipeRefreshLayout swipeLayout) { | |
mSwipeLayout = swipeLayout; | |
} | |
public void addScrollListener(RecyclerView.OnScrollListener listener){ | |
mScrollListeners.add(listener); | |
} | |
public boolean removeScrollListener(RecyclerView.OnScrollListener listener){ | |
return mScrollListeners.remove(listener); | |
} | |
public void setExpectedFirstVisiblePosition(int position){ | |
mExpectedVisiblePosition = position; | |
} | |
@Override | |
public void onScrollStateChanged(RecyclerView recyclerView, int newState) { | |
super.onScrollStateChanged(recyclerView, newState); | |
notifyScrollStateChanged(recyclerView,newState); | |
LinearLayoutManager llm = (LinearLayoutManager) recyclerView.getLayoutManager(); | |
int firstVisible = llm.findFirstCompletelyVisibleItemPosition(); | |
if(firstVisible != RecyclerView.NO_POSITION) | |
mSwipeLayout.setEnabled(firstVisible == mExpectedVisiblePosition); | |
} | |
@Override | |
public void onScrolled(RecyclerView recyclerView, int dx, int dy) { | |
super.onScrolled(recyclerView, dx, dy); | |
notifyOnScrolled(recyclerView, dx, dy); | |
} | |
private void notifyOnScrolled(RecyclerView recyclerView, int dx, int dy){ | |
for(RecyclerView.OnScrollListener listener : mScrollListeners){ | |
listener.onScrolled(recyclerView, dx, dy); | |
} | |
} | |
private void notifyScrollStateChanged(RecyclerView recyclerView, int newState){ | |
for(RecyclerView.OnScrollListener listener : mScrollListeners){ | |
listener.onScrollStateChanged(recyclerView, newState); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment