Android ChildFragmentManager().findFragmentById() always null

7.8k Views Asked by At

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!

2

There are 2 best solutions below

1
On BEST ANSWER

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().

4
On

You must add your child fragment dynamically. See here:

Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>. Nested fragments are only supported when added to a fragment dynamically.

ps. if you are planning to use nested fragments then be prepared for various strange behaviours, you can find them in bug reports to android platform:

https://code.google.com/p/android/issues/list?can=2&q=nested+fragment&sort=-opened&colspec=ID+Status+Priority+Owner+Summary+Stars+Reporter+Opened&cells=tiles