Dynamically added fragments are not deleted when the container is deleted

I'm trying to understand the bad behavior in fragments: methods onCreateViewand onActivityCreatedare called even a fragment, which is not "visible" in the layout.

If you use the code:

TestFragment testFragment = new TestFragment();
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.fragmentDetail, testFragment, "test");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();

replacing FrameLayout with the fragment identifierDetail with the fragment, and then you rotate the device, the fragment method is still called, even if the container is no longer in the portrait layout. This does not happen if you use the 'static' tag <fragment>. If you use a static fragment, fragment methods are called only when the fragment appears. Is it possible to achieve the same behavior without using a fragment tag? I need a way to avoid rendering a fragment if it is not in the layout.

thank

+2
source share
2 answers

I found one fix. It is slightly different from the proposed change in orientation orientation using fragments :

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
     if (!fragment.isInLayout() && container == null) return null;
     ...
     }

This way you can avoid the case where the fragment is statically placed in the layout (in this case, the container is null, but the isInLayout () method returns true. By the way, this is still strange for me this behavior.

+2
source

AFAIK, fragments work almost like Activities. They have the same life cycle. http://developer.android.com/reference/android/app/Fragment.html#Lifecycle So, if you do not have links to them, this will not make them private. They refer to the system and live on their own. So you have to finish them.

0

All Articles