Stop fragment from being recreated after resume?

Kaidul picture Kaidul · Aug 25, 2013 · Viewed 14k times · Source

I am using several fragments to be dynamically added into activity. Everything works fine, when I press back-button, the fragments go to backstack. And when I resume it, it appears. But everytime on Resume, it is recreating the fragment and call onCreateView. I know it is a normal behavior of the fragment lifecycle.

This is my onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View rootView = inflater.inflate(
            R.layout.competitive_programming_exercise, container, false);
    return rootView;
}

I want to stop those fragments from recreating. I tried with onSavedInstanstate but nothing is working. How can I accomplish that?

Answer

Arne Evertsson picture Arne Evertsson · Aug 19, 2014

In the Activity's onCreateView set the savedInstanceState to null before calling the super method. You could also remove only the keys "android:viewHierarchyState" and "android:fragments" from the savedInstanceState bundle. Here is code for the simple solution, nulling the state:

@Override
public void onCreate(Bundle savedInstanceState)
{
    savedInstanceState = null;
    super.onCreate(savedInstanceState);

    ...
}