Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragment doesn't call onSaveInstanceState when swiping ViewPager?

I'm having an issue with the ViewPager where my ListView is loosing it's scroll position.

The state of the ListView can easily be stored and restored using:

@Override
public View onCreateView (LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) 
{
    View v = inflater.inflate(R.layout.frag_cool_things, container, false);

    AdvListView listView = (AdvListView) v.findViewById(R.id.lv0);
    listView.setOnItemClickListener( mOnListItemClicked );

    if (null != savedInstanceState)
    {
        listView.onRestoreListViewInstanceState(savedInstanceState.getParcelable("list_state"));
    }

    mListView = listView;

    return v;
}

@Override
public void onSaveInstanceState (Bundle outState) 
{
    super.onSaveInstanceState(outState);

    outState.putParcelable("list_state", mListView.onSaveListViewInstanceState());
}

However the problem is that when fragments are being swiped onDestroyView() gets called but never calls onSaveInstanceState (Bundle outState).

Rotating the screen and such restores the ListView state just fine but swiping I can't figure out how to restore the list properly.

like image 713
Jona Avatar asked Dec 07 '11 21:12

Jona


1 Answers

Update 12/17/11:
I actually found the correct way to save the content of the Fragments. You must use FragmentStatePagerAdapter. This adapter properly saves the state of the fragment! :)

OLD:
Well I found a way to do this.. Please share your input if you believe this is a huge no no! :P

Here is my FragmentBase class that fixed this issue:

public abstract class FragmentBase extends Fragment
{
    private boolean mInstanceAlreadySaved;
    private Bundle mSavedOutState;

    @Override
    public View onCreateView (LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) 
    {
        if (null == savedInstanceState && null != mSavedOutState) {
            savedInstanceState = mSavedOutState;
        }

        mInstanceAlreadySaved = false;
        return onCreateViewSafe(inflater, container, savedInstanceState);
    }

    @Override
    public void onSaveInstanceState (Bundle outState) 
    {
        super.onSaveInstanceState(outState);
        mInstanceAlreadySaved = true;
    }

    @Override
    public void onStop() 
    {
        if (!mInstanceAlreadySaved)
        {
            mSavedOutState = new Bundle();
            onSaveInstanceState( mSavedOutState );
        }

        super.onStop();
    }

    public abstract View onCreateViewSafe (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);
}
like image 161
Jona Avatar answered Sep 29 '22 06:09

Jona