3

Learning how to use the OnScrollListener and I want to make a way I can detect everytime a new List item is visible when a user scrolls up or down in a listview, if the user scrolls down I want to make a counter increment by 1 for each new cell that enters the screen and if it scrolls up I want it to decrement, any help would go a long way, thanks.

counter = 0;
    list.setOnScrollListener(new OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {

        }

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

            // If list scroll up
            counter++;

            // If list scrolls down
            counter--;

        }
    });
Edmund Rojas
  • 6,376
  • 16
  • 61
  • 92

2 Answers2

3

I figured it out, the first visible item increments by one as you scroll down

counter = 0;
    list.setOnScrollListener(new OnScrollListener() {
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // Do nothing
        }

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

            if(firstVisibleItem > counter + 3 || firstVisibleItem < counter - 3){
                counter = firstVisibleItem;
                Toast.makeText(ListTestActivity.this,
                        "counter = " + counter,
                        Toast.LENGTH_LONG).show();
            }



        }
    });
Edmund Rojas
  • 6,376
  • 16
  • 61
  • 92
1

Use the firstVisibleItem variable. When it changes, adjust your count appropriately.

Khantahr
  • 8,156
  • 4
  • 37
  • 60
  • what should I compare firstvisibleitem against to determine if a new view is visible in either direction? – Edmund Rojas Dec 20 '12 at 21:50
  • Make a private class variable that holds the last visible item and compare it with `firstVisibleItem` every time `onScroll` is called. If they're different, update your private variable with the new visible item and adjust your counter. – Khantahr Dec 20 '12 at 21:54