Possible duplicate:
Separate back stack for each tab on Android using snippets
I recently started working on an application with fragments inside a tab host in FragmentActivity. The Android documentation says that this is necessary since the TabActivity class is now deprecated. To use fragments, I use the android v4 support library.
Currently, my application consists of a single tab within which fragments exist. To jump to the new snippets on the tab, I used the following code (which seems correct based on the documentation):
FragmentTransaction ft = fragmentManager.beginTransaction(); ft.replace(containerId, newFragment); ft.addToBackStack(null); ft.commit();
Everything was fine and good, until I pressed the Back key to go to the previous fragment, and realized that all my view state was largely destroyed .. it happened that the onCreateView () method called my previous fragment again, although his views were created earlier ... why is this? I searched around how to properly maintain state with fragments, but I cannot find decent documentation on this.
What did I try to use then
ft.add(containerId, newFragment);
instead
ft.replace(containerId, newFragment);
This actually worked pretty well in that my view state was saved - onCreateView () was not called every time my previous snippets were shown. However, I then began to notice that I could interact with components (button, etc.) from previous fragments lying below the current fragment, although I could not see the components !? I read somewhere that to save some state, use the following method:
public void onSaveInstanceState (Bundle outState)
I implemented this method, but it was never called! I also noticed that the bundles that passed with the onCreateView () and onActivityCreated () methods are always zero. Hasn't Google made it so difficult to achieve something like this, and should I miss something? Any help on how to properly maintain the viewing state of the fragment will be greatly appreciated!
Thanks.