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();
            }
        });
Share:
11,614
KiKo
Author by

KiKo

What can I say.....I'm newbie here :)

Updated on June 27, 2022

Comments

  • KiKo
    KiKo almost 2 years

    I have one ScrollView with one LinearLayout with TextViews. I want to detect when ScrollView is scrolling up or down to hide/show ActionBar.

  • KiKo
    KiKo over 9 years
    Than I need to add my new ExampleScrollView in xml file. Right?
  • tyczj
    tyczj over 9 years
    yes with the full class path ie. com.my.app.ExampleScrollView
  • KiKo
    KiKo over 9 years
    I get errors: Custom view ExampleScrollView is not using the 2- or 3-argument View constructors; XML attributes will not work
  • tyczj
    tyczj over 9 years
    well yeah you have to implement all the proper constructors