Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment view state within a tab host [duplicate]

Possible Duplicate:
Separate Back Stack for each tab in Android using Fragments

I've recently started working on an application with fragments inside a tab host within a FragmentActivity.. the Android documentation said to do this as the TabActivity class is now deprecated. In order to use fragments, I am using the android v4 support library.

Currently my app consists of one tab within which the fragments exist. To navigate to new fragments within the tab I have been using the following code (which seems to be correct based on the documentation):

FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(containerId, newFragment);
ft.addToBackStack(null);
ft.commit();

All was well and good until I hit the back key to navigate to a previous fragment and realised that all of my view state had pretty much been destroyed.. what was happening is that the onCreateView() method was being called again on my previous fragment even though its views had previously been created... why is this? I've searched around on how to properly maintain state with fragments but I can't seem to find decent documentation on this.

What I then tried was to use the

ft.add(containerId, newFragment);

instead of

ft.replace(containerId, newFragment);

This in fact worked quite well in that my view state was retained - onCreateView() was not called each time my previous fragments were shown. However, what I then began to notice was that I could interact with components (button, etc.) from previous fragments lying below the current fragment, even though I couldn't see the components!? I read somewhere that the following method should be used to save some state:

public void onSaveInstanceState (Bundle outState)

I implemented this method, however, it was never called! I also noticed that the bundles past to the onCreateView() and onActivityCreated() methods are always null. Surely Google has not made it this difficult to achieve something like this and I must be missing something? Any help on how to correctly maintain a fragment's view state will be greatly appreciated!

Thanks.

like image 229
Stephen Asherson Avatar asked Sep 16 '11 14:09

Stephen Asherson


1 Answers

Have a look at this question - I think the two may be related and you might be able to work around this issue.

Separate Back Stack for each tab in Android using Fragments

like image 145
Richard Le Mesurier Avatar answered Nov 15 '22 01:11

Richard Le Mesurier