Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ListView - scrolls back to top on update

I have a listview that gets additional views added on request, that's maintained by a BaseAdapter. How can I maintain scroll position after the update?

I know this has been asked a few times, but each time, the same solution has been put forward, which I have tried, which is to call adapter.notifyDataSetChanged(); after updating the ArrayList that contains the list contents.

How can I ensure that scroll position is maintained?

like image 534
ajacian81 Avatar asked Aug 09 '12 06:08

ajacian81


2 Answers

Implement an OnScrollListener in your activity class and then use the following code:

int currentFirstVisibleItem, currentVisibleItemCount, currentTotalItemCount;
public void onScroll(AbsListView view, int firstVisibleItem,
        int visibleItemCount, int totalItemCount) {
    this.currentFirstVisibleItem = firstVisibleItem;
    this.currentVisibleItemCount = visibleItemCount;
    this.currentTotalItemCount = totalItemCount;
}

public void onScrollStateChanged(AbsListView view, int scrollState) {
    this.currentScrollState = scrollState;
    this.isScrollCompleted();
}

private void isScrollCompleted() {

    if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
        if (this.currentVisibleItemCount > 0
                && this.currentScrollState == SCROLL_STATE_IDLE) {

            //Do your work
        }
    }
}

If you are using AsyncTask for updating your data, then you can include the following in your PostExecute() in order to maintain the Scroll position:

list.setAdapter(adapter);
list.setSelectionFromTop(currentFirstVisibleItem, 0);

I hope this helps.

like image 75
Shekhar Chikara Avatar answered Oct 15 '22 00:10

Shekhar Chikara


The approach I take is to call ListView.setSelection(position) to scroll to the desired position after the update.

Depending on where you're calling it from, you might need to call requestFocusFromTouch before calling setSelection in order to ensure the item gets positioned appropriately.

like image 21
Code Poet Avatar answered Oct 15 '22 01:10

Code Poet