Wednesday, December 05, 2012

List View scrolls back to top on Update Problem

0 comments
This is one problem that we have come across a lot of times. When we create a ListView and we try to include the facility to load more data in ListView, then this is a problem we come across very easily. So, whenever we will load more data in the ListView, it will scroll back to the top of the ListView. For this, I have written down the code that keeps the ListView at the current position and adds more items into the List.

The steps to do this are as follows:-
1. Implement an OnScrollListener in your activity class,
2. 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 OnPostExecute() in order to maintain the scroll position.

list.setadapter(adapter);
list.setSelectionFromTop(currentFirstVisibleItem, 0);
Hope this helps.. Cheers!!! Happy Droiding... :-)


Post a Comment