1

Is it possible to add fragments inside another fragment ?

Indeed, I have an Activity A which contains a fragment F1 and I want to add another fragment F1.1 in the fragment F1.

enter image description here

How can i do this.

I hope you understand my question

Bassem Jlassi
  • 187
  • 5
  • 11

2 Answers2

6

Suppose you have an activity layout file like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <fragment android:name="com.example.frag.MyFragment"
            android:id="@+id/list"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="match_parent" />
</LinearLayout>

This will create a fragment of type MyFragment in the activity, you can also do it programatically:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, fragment);
fragmentTransaction.commit();

R.id.fragment_container is the id of the view that will hold your fragment in the activity layout file, I normally use a frame layout.

Finally, for the nested fragment you can only do it programatically. The method is pretty similar to adding a fragment to the activity programatically, Inside the parent fragment you do:

Fragment nestedFragment = new MyFragment2();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.nested_frag, videoFragment).commit();

Once again R.id.nested_frag is the id of the container in the parent fragment layout file.

Levi Moreira
  • 11,917
  • 4
  • 32
  • 46
0

From fragment F1 you can use following to add new fragment :

    FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
    fragmentTransaction.replace(R.id.container, fragment);
    fragmentTransaction.commit();
Mirza Ahmed Baig
  • 5,605
  • 3
  • 22
  • 39