Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
});
like image 870
John Sardinha Avatar asked Dec 24 '22 04:12

John Sardinha


2 Answers

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);
        }
    });
like image 166
R. Zagórski Avatar answered Dec 28 '22 23:12

R. Zagórski


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

like image 31
antonio Avatar answered Dec 28 '22 23:12

antonio