少し前に、Fragmentの中でもFragmentを利用できることを知りました。
getChildFragmentManager()でFragmentManagerを取得すれば良いようです。
以下はサンプルです。
MainActivity.java
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Fragment fragment = NestFragment.newInstance(0);
getSupportFragmentManager().beginTransaction().add(R.id.content, fragment).commit();
}
public static class NestFragment extends Fragment {
private static final String ARG_ID = "id";
public static NestFragment newInstance(int id) {
Bundle args = new Bundle();
args.putInt(ARG_ID, id);
NestFragment fragment = new NestFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main, null);
int id = getArguments().getInt(ARG_ID);
if (id < 5) {
Fragment fragment = NestFragment.newInstance(id + 1);
getChildFragmentManager().beginTransaction().add(R.id.content, fragment).commit();
}
((TextView) view.findViewById(R.id.text)).setText(Integer.toString(id));
int colorId = ((id & 1) == 1) ? android.R.color.black : android.R.color.white;
view.setBackgroundColor(getResources().getColor(colorId));
return view;
}
}
}
layout/main.xml
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TEXT"
android:textColor="#888" />
<FrameLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp" >
</FrameLayout>
</LinearLayout>
表示するとこんな感じになります。(こんな使い方はしませんが)