4

Is it possible to check if a ScrollView is scrolled all its way in the top?

I want to check this so I can enable a SwipeRefreshLayout, otherwise keeping it disabled.

With a ListView it could be done like this, but there's no setOnScrollListener for ScrollViews

listView.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        boolean enable = false;
        if(listView != null && listView.getChildCount() > 0){
            // check if the first item of the list is visible
        boolean firstItemVisible = listView.getFirstVisiblePosition() == 0;
        // check if the top of the first item is visible
        boolean topOfFirstItemVisible = listView.getChildAt(0).getTop() == 0;
        // enabling or disabling the refresh layout
        enable = firstItemVisible && topOfFirstItemVisible;
    }
    swipeRefreshLayout.setEnabled(enable);
}
});
John Sardinha
  • 3,566
  • 6
  • 25
  • 55
  • isn't that: http://stackoverflow.com/questions/7318373/how-to-find-out-if-listview-has-scrolled-to-top-most-position working for you? – user2699706 Jun 25 '16 at 14:21
  • Your question asks if it is possible to check a `ListView` and then you give an answer on how to do it for a list view. You also mention a ScrollView out of the blue. If your question is about ScrollViews, can't you use `ScrollView.setOnScrollChangeListener` – Marcus Hooper Jun 25 '16 at 14:24
  • @MarcusHooper My bad, I meant ScrollView ... – John Sardinha Jun 25 '16 at 14:27

3 Answers3

8

This link might be helpful to You. It shows, how to set scroll listener for ScrollView. Then, refer to @antonio answer.

For your case it would be:

    mScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int scrollY = mScrollView.getScrollY(); //for verticalScrollView
            if (scrollY == 0) 
                swipeRefresh.setEnabled(true);
            else 
                swipeRefresh.setEnabled(false);
        }
    });
Community
  • 1
  • 1
R. Zagórski
  • 20,020
  • 5
  • 65
  • 90
1

You can use the getScrollY() method (from the View class)

antonio
  • 18,044
  • 4
  • 45
  • 61
1

In Kotlin:

scrollView.viewTreeObserver.addOnScrollChangedListener {
    if (!scrollView.canScrollVertically(1)) {
        // Bottom of scroll view.
    }
    if (!scrollView.canScrollVertically(-1)) {
        // Top of scroll view.
    }
}