整理したものはTech sheetsにあるよ

2017年6月9日金曜日

[Android]XMLでFragment in Fragment

みんなー、こんにちはー

今日は、AndroidのFragment in Fragmentに関する話題をお届け!

Android N(API 25)までは、Fragment用のレイアウトに<fragment>で子Fragmentを配置するとクラッシュするのは、みんな知ってるよね?

レイアウトは、こんな感じ。

activity_main.xml

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <fragment
        android:id="@+id/fragment_1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.mokelab.fragment.MainFragment"/>
</FrameLayout>


fragment_main.xml

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    <fragment
        android:id="@+id/fragment_1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:name="com.mokelab.fragment.ChildFragment"/>
</FrameLayout>

Activity -> MainFragment -> ChildFragment という感じで貼り付けてあるね。N(API 25)までだと、クラッシュしちゃう。

でもこれをAndroid O(API 26?)で実行すると、問題なく表示されるようになったよ!
詳しくはI/O 2017の動画も見てねー♪

ちなみに、ActivityにMainFragmentを貼り付ける部分をJava(Kotlin)コードで動的に追加してあげると、N以前でもクラッシュせずに済むよー