As explained here you can use onSaveInstanceState() to save data in the Bundle and retrieve that data in the onRestoreInstanceState() method.
Often setRetainState(true) is mentioned as way to keep the ui state in fragment, but it does not work for you because you are using the backstack.
So a good way for you could be to save the scrollposition in onSaveInstanceState() and restore it in onRestoreInstanceState() like this:
public class MyListFragment extends ListFragment {
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
int index = this.getListView().getFirstVisiblePosition();
View v = this.getListView().getChildAt(0);
int top = (v == null) ? 0 : v.getTop();
outState.putInt("index", index);
outState.putInt("top", top);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
[...]
if (savedInstanceState != null) {
// Restore last state for checked position.
index = savedInstanceState.getInt("index", -1);
top = savedInstanceState.getInt("top", 0);
}
if(index!=-1){
this.getListView().setSelectionFromTop(index, top);
}
}
Further more you can find a more detailed similiar example here.
Bundle
and OverridingonSavedInstance()
? – Annamarieannamese