androidandroid-fragmentsfragment-lifecycle

Distinguishing static fragments from dynamic ones


Writing an android library, I'm listening to fragments' life-cycle using supportFragmentManager.registerFragmentLifecycleCallbacks. Having the fragment object in the callbacks, how can I check whether the fragment is a static fragment (defined in the xml file) or a dynamic one (defined in a container like FrameLayout)?


Solution

  • I found the solution myself and it was actually a pretty easy one.

    The Fragment class has a method called isInLayout() which returns true if the fragment has been created using the <fragment> tag.

    Here is the documentation for the method:

    public final boolean isInLayout ()

    Return true if the layout is included as part of an activity view hierarchy via the <fragment> tag. This will always be true when fragments are created through the <fragment> tag, except in the case where an old fragment is restored from a previous state and it does not appear in the layout of the current state.