How to maintain a scroll position of a ListView

How to keep scroll position of ListView when selecting one item in ListView and I want to return to the same ListView.

Suppose we have two fragments - ListFragment and SomeOtherFragment. We are replacing ListFragment with SomeOtherFragment.

FragmentManager manager = getFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.content_frame, fragment); transaction.addToBackStack(null); transaction.commit(); 
+6
android
source share
3 answers

The best solution I know

// Save ListView state (= enable scroll position) as a Parcelable parameter

 Parcelable state = listView.onSaveInstanceState(); 

// Restore previous state (including selected item index and scroll position)

 listView.onRestoreInstanceState(state); 

You can also restore the last saved position even after installing the adapter as -

 // Save the ListView state (= includes scroll position) as a Parceble Parcelable state = listView.onSaveInstanceState(); // eg set new items listView.setAdapter(adapter); // Restore previous state (including selected item index and scroll position) listView.onRestoreInstanceState(state); 

You can also find it here for more details.

+9
source share

When you click on the ListFragment line, save the position in SharedPreference

 <shared_pref_object>.putInt("scroll_position",position); 

Use this when you return with OtherFragment ListFragment

 <editor_obj>.getInt("scroll_position",0); 

set this as the scroll position:

 listview.setSelection(<editor_obj>.getInt("scroll_position",0)); 
+2
source share

I am really curious why there is no good and optimized solution for this general problem. As I understand it, everyone decided in their own way. but I want to introduce my own path by trying them all:

Inside the ListFragment, declare two int variables to hold the scroll position:

 public static class MyListFragment extends ListFragment { private int listIndex = -1; private int listTop = 0; 

Then override onPause () and onResume () to save and restore the scroll positions of the ListView as follows:

 @Override public void onResume() { super.onResume(); //after setting adapter and your arbitrary codes if(listIndex!=-1){ this.getListView().setSelectionFromTop(index, top); } } @Override public void onPause() { super.onPause(); try { listIndex = getListView().getFirstVisiblePosition(); View v = getListView().getChildAt(0); listTop = (v != null) ? v.getTop() : 0; } catch (Exception e) { e.printStackTrace(); } } 

The desire to reduce pain !: Blush:

0
source share

All Articles