Detect if a ScrollView is scrolling up or down - Android
11,614
Solution 1
you need to create a class that extends ScrollView
public class ExampleScrollView extends ScrollView
and then Override onScrollChanged
that gives you the old and new scroll positions and from there you can detect which direction
protected void onScrollChanged(int l, int t, int oldl, int oldt)
Solution 2
check this out
scrollView.setOnTouchListener(new View.OnTouchListener() {
float y0 = 0;
float y1 = 0;
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (motionEvent.getAction() == MotionEvent.ACTION_MOVE) {
y0 = motionEvent.getY();
if (y1 - y0 > 0) {
Log.i("Y", "+");
AnimateFloat(true);
} else if (y1 - y0 < 0) {
Log.d("Y", "-");
AnimateFloat(false);
}
y1 = motionEvent.getY();
}
return false;
}
});
Solution 3
I think I am little bit late to answer this but here is my answer
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
float y = 0;
@Override
public void onScrollChanged() {
if (scrollView.getScrollY() > y) {
Log.v("Message", "Scrolls Down");
} else {
Log.v("Message", "Scrolls Up");
}
y = scrollView.getScrollY();
}
});
Comments
-
KiKo almost 2 years
I have one
ScrollView
with oneLinearLayout
withTextView
s. I want to detect whenScrollView
is scrolling up or down to hide/showActionBar
. -
KiKo over 9 yearsThan I need to add my new ExampleScrollView in xml file. Right?
-
tyczj over 9 yearsyes with the full class path ie.
com.my.app.ExampleScrollView
-
KiKo over 9 yearsI get errors: Custom view ExampleScrollView is not using the 2- or 3-argument View constructors; XML attributes will not work
-
tyczj over 9 yearswell yeah you have to implement all the proper constructors