Kurlicue Kurlicue - 5 months ago 13
Java Question

Check if a ScrollView has reached the top of the layout

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);
}
});

Answer

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);
        }
    });