trocchietto
trocchietto

Reputation: 2617

Orientation: restore ListView position that is inside a Fragment

I went trough a famous post in SO, Maintain/Save restore scroll position but does not help me at all.

I have a ListView inside a Fragment, if I change the orientation, I would like that saveInstance Bundle will save my position. I have

 private static final String LIST_STATE = "listState";
private Parcelable mListState = null;

@Override
public void onSaveInstanceState(Bundle outState) {

    super.onSaveInstanceState(outState);

    mListState = listView.onSaveInstanceState();
    outState.putParcelable(LIST_STATE, mListState);

    }

and does not matter if I put in OnCreateView or in onActivityCreated the following code

  if(savedInstanceState!=null) {
       mListState = savedInstanceState.getParcelable(LIST_STATE);
       listView.onRestoreInstanceState(mListState);

the up position of the list is not restored at all. I can easily see from the debug in Bundle that the debug recognize in the Bundle the position,

AbsListView.SavedState{3d7562e0 selectedId=-9223372036854775808 firstId=25 viewTop=-38 position=5 height=717 filter=null checkState=null}

I even tried to extract from the Bundle this position in an isolated way instead of all the values, but without success.

Upvotes: 1

Views: 233

Answers (2)

trocchietto
trocchietto

Reputation: 2617

Found it!

The solution is

  @Override
    public void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);

mPosition2=listView.getFirstVisiblePosition();

if(mPosition2!=0) {
    mPosition = mPosition2;
}

        if (mPosition != ListView.INVALID_POSITION) {
            outState.putInt(SELECTED_KEY, mPosition);
        }
        }

and in onCreateView

  if (savedInstanceState != null && savedInstanceState.containsKey(SELECTED_KEY)) {
            mPosition = savedInstanceState.getInt(SELECTED_KEY);

        }

finally I have a loader that query a content provider at end of onLoadFinished( but you can put you just where you need)

  if (mPosition != ListView.INVALID_POSITION) {

        listView.setSelection(mPosition);

I have also tried listView.smoothScrollToPosition(mPosition) but is not working at the moment, but never mind it works really well to me.

Upvotes: 1

mdDroid
mdDroid

Reputation: 3195

add following code inside fragment

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setRetainInstance(true);
}

Upvotes: 1

Related Questions