Rooboo
Rooboo

Reputation: 253

Find Fragment in Fragment

I got a fragment which contains a fragment, and I want to do stuff with it in onViewCreated or onCreateView. How can I find that inner fragment?

Here is the containerfragment:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:padding="@dimen/activity_horizontal_margin"
            tools:context="xx.activity.fragment.SalesFragment">
<fragment android:id="@+id/fragment_category"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/priceEdit"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="10dp"
        android:name="xxfragment"
        tools:layout="@layout/fragment_category"/>
</RelativeLayout>

It is not possible to find that inner fragment_category with the FragmentManager

FragmentManager fm = getActivity().getSupportFragmentManager();
CategoryFragment catFrag = (CategoryFragment) 
fm.findFragmentByTag(CategoryFragment.ID);

returns null.

Do I have to get the FragmentManager to know, that there is another fragment, or are there other possibilities to find that CategoryFragment?

Upvotes: 1

Views: 5110

Answers (1)

telkins
telkins

Reputation: 10540

You may need to use the child FragmentManager up to API 28, or the androidx child FragmentManager afterwards to interact with nested fragments.

FragmentManager fm = parentFragment.getChildFragmentManager();

Upvotes: 11

Related Questions