Reputation: 3076
I am trying to add nested child Fragments into a parent Fragment.
All works fine but....
At first my code:
public class FragmentDatasheetWithHeader extends Fragment {
private long mRowId;
private String mSid;
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final ScrollView scrollView = new ScrollView(getActivity());
final LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setId(4711);
linearLayout.setOrientation(LinearLayout.VERTICAL);
scrollView.addView(linearLayout);
createUI();
return scrollView;
}
private void createUI() {
final FragmentProductDetailHeader fragmentHeader = FragmentProductDetailHeader.newInstance(this.mRowId, FragmentProductDetailHeader.HEADERTYPE_SMALL);
final FragmentDatasheet fragmentDatasheet = FragmentDatasheet.newInstance(this.mRowId, this.mSid);
final FragmentManager fragmentManager = getChildFragmentManager();
fragmentManager.beginTransaction().add(4711, fragmentHeader, "fragmentHeader").commit();
fragmentManager.beginTransaction().add(4711, fragmentDatasheet, "fragmentDatasheet").commit();
}
}
Now my problem:
In the Developer options I activated "Don't keep activities (Destroy every activity as soon the user leaves it)"
When the activity with the FragmentDatasheetWithHeader is open and the app goes into background and comes back to foreground the nested Fragments are doubled. But it only appears if the container for the nested Fragments is a LinearLayout. If the container is a FrameLayout the nested Fragments are not doubled.
What's going wrong?
Upvotes: 1
Views: 4668
Reputation: 45493
If the container is a FrameLayout the nested Fragments are not doubled.
That's potentially not true. It is more likely that the new fragments are just sitting on top of the old ones, effectively obscuring them. Hence, the underlying issue is probably the same, the visual effect is just different because of how the various ViewGroup
implementations arrange their children.
That being said, there is an easy way to tell whether your fragment is 'created' freshly, or 'restored' from a previous state: by looking at the Bundle savedInstanceState
parameter that gets passed in to onCreateView()
(and various other life cycle related methods, like onActivityCreate()
etc.).
More specifically, you will probably want to add something like this to onCreateView()
:
if (savedInstanceState == null) createUI();
That way the fragments will only be added when there isn't a previous state to restore from. If there is a previous state, the framework should restore the old fragments in stead. In the latter case, you can get a handle on the restored fragments by looking them up by tag..
Upvotes: 2