Previously we have learned some basics about using Fragments inside activtiy.
Fragments are very useful. However until recently fragments could not be used inside other fragment. That is you Activty can have multiple fragments ,but fragments cannot have fragments inside them.
With Android 4.2 APIv17 there was support for Nested Fragments Where you can use fragment inside other fragment. However there is a limitation that your fragment must be dynamic. There is no option to use <fragment> tags.
Here's a demo of using fragment inside fragment.
We will make use of our sample that we have been working in previous posts. We will change FragmentA. Here's a new Layout for FragmentA.<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="I am FragmentA" /> <FrameLayout android:id="@+id/child_fragment" android:layout_width="fill_parent" android:layout_height="200dip" /> </LinearLayout>We use FrameLayout wherever we want our fragment to be . And so the updated FragmentA will be
import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FragmentA extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = (View) inflater.inflate(R.layout."name of layout", container, false); return view ; } }Now the child Fragment let it be FragmentC
import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class FragmentC extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { TextView textView=new TextView(getActivity()); textView.setText("Hello I am fragment C"); return textView; } }And to add it dynamically to your FragmentA
Fragment fragmentC = new FragmentC(); FragmentTransaction transaction = getChildFragmentManager().beginTransaction(); transaction.add(R.id.child_fragment, fragmentC ).commit();Use getParentFragment() to get the reference to parent similar to getActivity that gives reference of parent Activtiy.