Detect Scroll Up & Scroll down in ListView

chiranjib picture chiranjib · May 28, 2013 · Viewed 122.1k times · Source

I have the following requirement:

  • At first, data for page no: 2 is fetched from the server & the items are populated in a ListView.

Considering that both the prev page & next page are available in a scenario, the following code has been added:

 if(prevPageNo > 0){
    mListViewActual.setOnScrollListener(this);
 }

 if(nextPageNo > 0){
    mListViewActual.setOnScrollListener(this);
 }

What conditions should I put to detect scroll up & scroll down on the following methods:

  1. void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount)
  2. void onScrollStateChanged(AbsListView view, int scrollState)

After the action: scroll up & scroll down is detected , accordingly a service will be called with either the prev page no or next page no , to fetch the items to be populated in the Listview.

Any inputs will be helpful.

Gone through the following links but its not returning the correct scroll up / scroll down action:

link 1 link 2

Answer

Sunil Kumar picture Sunil Kumar · Jun 10, 2013

try using the setOnScrollListener and implement the onScrollStateChanged with scrollState

setOnScrollListener(new OnScrollListener(){
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
      // TODO Auto-generated method stub
    }
    public void onScrollStateChanged(AbsListView view, int scrollState) {
      // TODO Auto-generated method stub
      final ListView lw = getListView();

       if(scrollState == 0) 
      Log.i("a", "scrolling stopped...");


        if (view.getId() == lw.getId()) {
        final int currentFirstVisibleItem = lw.getFirstVisiblePosition();
         if (currentFirstVisibleItem > mLastFirstVisibleItem) {
            mIsScrollingUp = false;
            Log.i("a", "scrolling down...");
        } else if (currentFirstVisibleItem < mLastFirstVisibleItem) {
            mIsScrollingUp = true;
            Log.i("a", "scrolling up...");
        }

        mLastFirstVisibleItem = currentFirstVisibleItem;
    } 
    }
  });