How to know if the user has scrolled to the top or bottom of a listview/scrollview

I have found a solution by checking the offset of the first or the last item, when the offset of those items is 0 then we have reached the bottom/top of the listview.

    listview.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (firstVisibleItem == 0) {
                // check if we reached the top or bottom of the list
                View v = listview.getChildAt(0);
                int offset = (v == null) ? 0 : v.getTop();
                if (offset == 0) {
                    // reached the top:
                    return;
                } 
            } else if (totalItemCount - visibleItemCount == firstVisibleItem){
                View v =  listview.getChildAt(totalItemCount-1);
                int offset = (v == null) ? 0 : v.getTop();
                if (offset == 0) {
                    // reached the bottom:
                    return;
                }
            }               
        }
    });

Try this way

 list.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {

            }

        int mPosition=0;
        int mOffset=0;

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub
             int position = list.getFirstVisiblePosition();
               View v = list.getChildAt(0);
                int offset = (v == null) ? 0 : v.getTop();

                if (mPosition < position || (mPosition == position && mOffset < offset)){
                     // Scrolled up 

                } else {
                     // Scrolled down

                }
        }
    }); 

Tags:

Android