Skip to content

Instantly share code, notes, and snippets.

@zhanghai
Last active May 8, 2019 07:17
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save zhanghai/b65098bc17a88c7b8192 to your computer and use it in GitHub Desktop.
Save zhanghai/b65098bc17a88c7b8192 to your computer and use it in GitHub Desktop.
RecyclerView.OnScrollListener that reports scrolled up/down or reached top/bottom.
/*
* Copyright (c) 2015 Zhang Hai <Dreaming.in.Code.ZH@Gmail.com>
* All Rights Reserved.
*/
package com.example.android;
import android.support.v7.widget.RecyclerView;
public abstract class OnVerticalScrollListener extends RecyclerView.OnScrollListener {
@Override
public final void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (!recyclerView.canScrollVertically(-1)) {
onScrolledToTop();
} else if (!recyclerView.canScrollVertically(1)) {
onScrolledToBottom();
}
if (dy < 0) {
onScrolledUp(dy);
} else if (dy > 0) {
onScrolledDown(dy);
}
}
public void onScrolledUp(int dy) {
onScrolledUp();
}
public void onScrolledDown(int dy) {
onScrolledDown();
}
public void onScrolledUp() {}
public void onScrolledDown() {}
public void onScrolledToTop() {}
public void onScrolledToBottom() {}
}
/*
* Copyright (c) 2015 Zhang Hai <Dreaming.in.Code.ZH@Gmail.com>
* All Rights Reserved.
*/
package com.example.android;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.ViewConfiguration;
public abstract class OnVerticalScrollWithPagingSlopListener extends OnVerticalScrollListener {
private final int mPagingTouchSlop;
// Distance in y since last idle or direction change.
private int mDy;
public OnVerticalScrollWithPagingSlopListener(Context context) {
mPagingTouchSlop = ViewConfiguration.get(context).getScaledPagingTouchSlop();
}
@Override
public final void onScrollStateChanged(RecyclerView recyclerView, int newState) {
if (newState == RecyclerView.SCROLL_STATE_IDLE) {
mDy = 0;
}
}
@Override
public final void onScrolledUp(int dy) {
mDy = mDy < 0 ? mDy + dy : dy;
if (mDy < -mPagingTouchSlop) {
onScrolledUp();
}
}
@Override
public final void onScrolledDown(int dy) {
mDy = mDy > 0 ? mDy + dy : dy;
if (mDy > mPagingTouchSlop) {
onScrolledDown();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment