Ziem
Ziem

Reputation: 6697

Strange fragment behaviour - empty container in view hierarchy after screen rotation

I encountered very strange problem with fragments. In my case I have fragment which is placed inside activity. It has two type of layout: layout - with Frame Layout with list_container id layout-land - with two Layout: list_container and detail_container.

When user enters activity in portrait mode he sees TestListFragment. When he clicks one of the list element TestDetailFragment is added to backstack. Next, when user rotates screen TestDetailFragment is removed from backstack and placed inside layout with id detail_container. How strange part appears, when inspecting view hierarchy there are two list_containers (one is empty and is over the rest of the content causing view overlap). onActivityCreated in TestFragment is triggered twice.

I'm including hierarchy view and screens:

Source code:

Is this normal behavior? How to get rid of this layout?

Upvotes: 1

Views: 468

Answers (2)

CommonsWare
CommonsWare

Reputation: 1006759

When you nest fragments (i.e., have a fragment host a fragment), the child fragments need to be set up either by:

  • having the parent fragment inflate a layout containing <fragment> tags

  • having the parent fragment use getChildFragmentManager() when executing a FragmentTransaction to add the child fragments

In this case, the code in the question is using getActivity().getSupportFragmentManager(), not getChildFragmentManager().

To be honest, I cannot completely understand how this resulted in the cited symptoms, but according to the comments on the question, it helped.

Upvotes: 1

Ciro Rizzo
Ciro Rizzo

Reputation: 492

When Android detect rotation it destroyes the running activity and create a new one, so if you have a behaviour on onCreate() and onDestroy() of the activity, keep in mind that. Take care also for Fragment that has a further event to manage and is related on the attached Activity onAttach()

Upvotes: 0

Related Questions