@Override protected void onSaveInstanceState(Bundle outState) { outState.putInt("scroll_position", getListView().getFirstVisiblePosition()); outState.putInt("selected_item", getListView().getSelectedItemPosition()); super.onSaveInstanceState(outState); }
@Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); int scrollPos = savedInstanceState.getInt("scroll_position", 0); int selectedItem = savedInstanceState.getInt("selected_item", -1); getListView().setSelectionFromTop(scrollPos, 0); getListView().setItemChecked(selectedItem, true); }In this example, we are restoring the saved state during activity recreation. We retrieve the saved scroll position and selected item values using the same keys, and then use the ListView methods setSelectionFromTop and setItemChecked to restore these values. This package library is a part of the Android SDK library.