動的生成方法も静的生成方法も簡単に知りたい人むけ。

 fragmentはAndroidStudioのプロジェクトツリービューの右クリックからNew→Fragment→Fragment(New)から作成する。するとフラグメントのレイアウトを設定するxmlファイルや、実装の基本的なテンプレートが生成される。そのテンプレートは便利なので、基本的にこれを利用するようにする。このテンプレートが何をしようとしているかの解説はこちらへ
 レイアウトファイルに静的に生成する場合は、レイアウトファイルを開いてデザインタブからfragmentをドラッグアンドドロップして設置するだけ。そうすると、どのフラグメントを表示させるのか聞かれるので設定をする。後はデザインに合わせて下記のように設定すればいい。
 今回は動的に生成するためにconstraintLayoutをその下に一つ設定している。fragmentを生成できるのはviewGroupを継承するUI部品であれば何でもいい。
 なお、表示させるアクティビティ側では、Sub01Fragment.OnFragmentInteractionListenerというインターフェースを実装しておくこと。
 

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnNext"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="NextPage"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

<!--静的に生成する場合にはfragmentを利用する--> <fragment android:id="@+id/fragment01" android:name="com.example.to.testlifecycleapplication.Sub01Fragment" android:layout_width="0dp" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/btnNext" />
<!--動的に生成する場合には、何らかのviewを配置しておく。--> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/crLayout" android:layout_width="0dp" android:layout_height="match_parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toBottomOf="@id/fragment01"> </android.support.constraint.ConstraintLayout> </android.support.constraint.ConstraintLayout>
 動的に生成する場合には下記のように生成する。なおFragmentManagerはandroid.app.FragmentManagerと、android.support.v4.app.FragmentManagerがあるので注意。同じ名前だが型が違うと怒られるのでimport間違いに注意。なお使うのはv4のほうがバグが直っているので、それを利用すること。AndroidStudioが自動的に生成するFragmentもv4のほうが使われているので同じにしないとコンパイルが通らない。
 具体的には下記のソースで生成する。AndroidStudioが作るテンプレートには自分自身のインスタンスを生成するコンパニオンオブジェクトがあるので、これを利用して生成する。テンプレでは任意の文字を引数に渡すように作られているが、動的に生成してフラグメント側で何かしらの処理を行いたい場合は、ここで文字なり数字なりを渡してあげてフラグメント側で処理を行うようにする。コンストラクタを呼び出して引数を渡すのはよくないようだ。


val fragmentTransaction: FragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.also {
    it.add(R.id.crLayout, Sub01Fragment.newInstance("", ""))
    it.commit()
}