frieza frieza - 6 months ago 24
Android Question

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

In android, a fragment (say

FragA
) gets added to the backstack and another fragment (say
FragB
) comes to the top. Now on hitting back
FragA
comes to the top and the
onCreateView()
is called. Now I had
FragA
in a particular state before
FragB
got pushed on top of it.

My Question is how can I restore
FragA
to its previous state ? Is there a way to save state (like say in a Bundle) and if so then which method should I override ?

Answer

In fragment guide FragmentList example you can find:

@Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("curChoice", mCurCheckPosition);
    }

Which you can use later like this:

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
            // Restore last state for checked position.
            mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
        }
}

I'm a beginner in Fragments but it seems like solution of your problem ;) OnActivityCreated is invoked after fragment returns from back stack.