Search code examples
androidandroid-fragmentschild-fragment

Android ChildFragmentManager().findFragmentById() always null


I stumbled into a crazy little 'bug', or i'm just doing something wrong. I am trying to get the reference to a fragment that is inside a fragment. So we have ParentFragment, that is a child of MainActivity. I can get a reference to this ParentFragment without a problem, because the ParentFragment is added to the MainActivity via code:

ParentFragment fragment = new ParentFragment();

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

transaction.replace(R.id.fragmentPlaceholder, fragment);
transaction.commit();

I have added a ChildFragment to the ParentFragment via XML like this:

parent_fragment.xml

<RelativeLayout ... etc>
    .. some other views, findViewById('') works great on these.
    <fragment
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:id="@+id/childFragment1"
        android:tag="1"
        class="com.my.package.ChildFragment"
        android:name="com.my.package.ChildFragment"
        tools:layout="@layout/child_fragment" />
</RelativeLayout>

All works fine, the ChildFragment(s) show up in the ParentFragment. The only thing is; i cannot find the fragmentById.

I have tried multiple ways of achieving this, how it should be done (?) :

getChildFragmentManager().findFragmentById(R.id.childFragment1)

Didn't work. Also, getting the Activity and using that fragment manager doesn't work (.. of course).

I have also tried getting all fragments in the ChildFragmentManager, iterating over them etc. But this always returns null:

getChildFragmentManager().getFragments()

Do you have any idea why this is happening? Can't i use the ChildFragrentManager if the fragments are not added via code?

Thanks!


Solution

  • If you want to use nested Fragments and be able to get a reference to them via findFragmentById you cannot use the support package.

    I changed all getSupportFragmentManager()'s to getFragmentManager() and replaced all FragmentActivity's with regular Activity's.

    Now it works as expected, just call getChildFragmentManager().findFragmentById().