How can I save the ListView's scroll position when I choose one item in ListView, and I want to return back in same ListView .
Suppose we have two fragments – ListFragment and SomeOtherFragment. We replace ListFragment with SomeOtherFragment.
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();
The best solution I know
// Save the ListView state (= includes scroll position) as a Parcelable
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 setting adapter as -
// Save the ListView state (= includes scroll position) as a Parceble
Parcelable state = listView.onSaveInstanceState();
// e.g. set new items
listView.setAdapter(adapter);
// Restore previous state (including selected item index and scroll position)
listView.onRestoreInstanceState(state);
You can also refer here for more details.
When you click on row of ListFragment
, save the position in SharedPreference
<shared_pref_object>.putInt("scroll_position",position);
Use this when you come back from OtherFragment
-> ListFragment
<editor_obj>.getInt("scroll_position",0);
set this as scroll position :
listview.setSelection(<editor_obj>.getInt("scroll_position",0));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With