0

I read How to maintain the position of ListView

That solution only works if the activity/fragment is not destroyed. If it is, like with a screen rotation, I think you need to put the scroll position into a bundle in onSaveInstanceState. Otherwise, when resuming the activity/fragment, the index will be 0 because it was not only stopped, but destroyed after rotating the screen.

So I saved the scroll position in my fragment's bundle in onSaveInstanceState and set the position in onActivityCreated:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt("scrollPos", listv.getFirstVisiblePosition());
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
....
int startIndex;
    if(savedInstanceState == null)
        startIndex = 0;
    else
        startIndex = savedInstanceState.getInt("scrollPos");
    questionsLV.setSelectionFromTop(startIndex, 0);
    return v;
}

I see the index saved in onActivityCreated after I rotate the screen, but my listview still starts from the top; why?

Community
  • 1
  • 1
HukeLau_DABA
  • 2,384
  • 6
  • 33
  • 51
  • put it in your oncreate method – Hades Oct 13 '14 at 03:15
  • you need to restore the position after the list has been populated, the problem is, in onActivityCreated the list is empty. Issue the setSelectionFromTop from a point later in our code when you are sure that the list has been initialized. – rupps Oct 13 '14 at 03:44
  • in oncreate I save the index. in oncreateView before I set the adapter, then call setSelectionFromTop. The debugger shows the saved index value, but the view it returns still starts at index 0. See updated post. – HukeLau_DABA Oct 13 '14 at 03:57

0 Answers0