Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding onScrolling listener to the android ListView

just wanted to ask is there a possibility to bind some listener to the ListView scroll event.

What I would like to achieve is that once ListView have been scrolled to the bottom I would like to ask server for more data if any is there.

I know that there is a function like: getLastVisiblePosition() but I assume it must bu used in some kind of listener in order to compare with currently last visible position, am I right ?

cheers, /Marcin

like image 402
Marcin Avatar asked Dec 13 '10 19:12

Marcin


1 Answers

Just to extrapolate on TomTo's answer, some thoughts on how you might do this (theoretical, I haven't tried this in practice):

ListView lv = (ListView)findViewById(R.id.list_view);
lv.setOnScrollListener(new OnScrollListener() {
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, 
        int visibleItemCount, int totalItemCount) {
        //Check if the last view is visible
        if (++firstVisibleItem + visibleItemCount > totalItemCount) {
            //load more content
        }
    }
});

Since firstVisibleItem is returns an index (0-based), I increment by one to get the actual item number. Then, if that, plus the number of visible items, is greater than the total number of items, then in theory the last view should be visible. Shouldn't be a problem, but keep in mind this isn't called till the scrolling is finished.

like image 155
Kevin Coppock Avatar answered Oct 27 '22 01:10

Kevin Coppock