jorgehcb
6/19/2015 - 6:29 PM

[Android] Save scroll position when returning to a ListView 2

Save scroll position when returning to a ListView 2

Parcelable state;

@Override
public void onPause() {    
    // Save ListView state @ onPause
    Log.d(TAG, "saving listview state @ onPause");
    state = listView.onSaveInstanceState();
    super.onPause();
}
...

@Override
public void onViewCreated(final View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    // Set new items
    listView.setAdapter(adapter);
    ...
    // Restore previous state (including selected item index and scroll position)
    if(state != null) {
        Log.d(TAG, "trying to restore listview state..");
        listView.onRestoreInstanceState(state);
    }
}

/*
I think this is the best answer as this method restores the exact scroll position and not only the first visible item. –  max.weller Jul 2 '12 at 10:52 

Great answer but won't work when dynamically loading content and you want to save state in the onPause() method. –  Gio Sep 18 '12 at 12:47

great solution. Just one Problem. If the items are big and you scroll, but the first item is still visible the list jumps back to top. if you scroll to the second item or anywhere else everything works –  passsy Jul 26 '13 at 3:34
*/