ぎじゅつめもブログ

主にアプリ開発の技術メモを残していきます。

【Android】Fragmentを入れ子にする

Fragmentを入れ子(ネスト)にするメモです。
(確認環境:Android4.1)

下図のようなイメージを例にとります。

f:id:tsuyushiga:20140930234902p:plain

まず親Fragmentである Fragment 1 です。
・Fragment1.java

//..略
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
//..略

public class Fragment1 extends Fragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_hoge, null);
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		FragmentTransaction transaction = getChildFragmentManager()
				.beginTransaction();
		Fragment childFragment1 = new ChildFragment1();
		Fragment childFragment2 = new ChildFragment2();
		transaction.add(R.id.child_fragment_1, childFragment1, "child_1");
		transaction.add(R.id.child_fragment_2, childFragment2, "child_2");
		transaction.commit();
	}
}

親フラグメントのレイアウトは下記のようにします。
・fragment_hoge.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <FrameLayout
        android:id="@+id/child_fragment_1"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"/>

    <FrameLayout
        android:id="@+id/child_fragment_2"
        android:layout_width="match_parent"
        android:layout_height="0dip"
        android:layout_weight="1"/>

</LinearLayout>

上記のようにimportをサポートライブラリにするとAndroid1.6から使えるようです。
また、Fragmentをネストする場合は、動的に追加しなければならないようです。

子Fragmentについては省略します。。

以上です。

※参考
Fragmentをネストする際の注意点 - Just for Fun
Android 4.2 APIs | Android Developers