Created
May 7, 2015 14:13
-
-
Save hector6872/9770bd4ac39bc4a75420 to your computer and use it in GitHub Desktop.
ObservableScrollView
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 ObservableScrollView extends ScrollView { | |
private static final int DEFAULT_THRESHOLD_DP = 4; | |
private ScrollDirectionListener scrollDirectionListener; | |
private int scrollThreshold; | |
public ObservableScrollView(Context context) { | |
this(context, null); | |
} | |
public ObservableScrollView(Context context, AttributeSet attrs) { | |
this(context, attrs, 0); | |
} | |
public ObservableScrollView(Context context, AttributeSet attrs, int defStyleAttr) { | |
super(context, attrs, defStyleAttr); | |
init(context); | |
} | |
private void init(Context context) { | |
scrollThreshold = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, DEFAULT_THRESHOLD_DP, context.getResources().getDisplayMetrics()); | |
} | |
@Override | |
protected void onScrollChanged(int x, int y, int oldX, int oldY) { | |
super.onScrollChanged(x, y, oldX, oldY); | |
if (Math.abs(y - oldY) > scrollThreshold && scrollDirectionListener != null) { | |
if (y > oldY) { | |
scrollDirectionListener.onScrollUp(Math.abs(y - oldY)); | |
} else { | |
scrollDirectionListener.onScrollDown(Math.abs(y - oldY)); | |
} | |
} | |
} | |
public void setScrollThresholdInPx(int px) { | |
scrollThreshold = px; | |
} | |
public void setScrollThresholdInDp(Context context, float dp) { | |
scrollThreshold = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, context.getResources().getDisplayMetrics()); | |
} | |
public void setOnScrollDirectionListener(ScrollDirectionListener listener) { | |
scrollDirectionListener = listener; | |
} | |
public interface ScrollDirectionListener { | |
void onScrollDown(int pixels); | |
void onScrollUp(int pixels); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment