LoginSignup
53
53

More than 5 years have passed since last update.

Fragment のテンプレート

Last updated at Posted at 2014-01-18

自分のFragmentを作る時にテンプレとして書く必要のあるものを以下にまとめておく。

内容はFragment初期化用のstaticメソッド。
Fragmentはデフォルトコンストラクタ以外のコンストラクタを持っていると、フレームワークがライフサイクル管理しきれなくなる。その理由は、Fragment | Android Developers にある通り。

All subclasses of Fragment must include a public empty constructor. The framework will often re-instantiate a fragment class when needed, in particular during state restore, and needs to be able to find this constructor to instantiate it. If the empty constructor is not available, a runtime exception will occur in some cases during state restore.
package sample.fragment;

import android.support.v4.app.Fragment;

public class MyFragment extends Fragment {
    // メモリ不足による破棄後からの復帰時にフレームワークがリフレクションで呼びだすコンストラクタ
    public MyFragment() {}

    // 自分のコードから Fragment の初期化に使うメソッド
    public static MyFragment newInstance() {
        MyFragment fragment = new MyFragment();
        // 以下二行は、Fragment に初期化用の変数を渡したいときに使う
        // Bundle arguments = new Bundle();
        // fragment.setArguments(arguments);
        return fragment;
    }
}

IDE でテンプレを設定しておくと便利。

AndroidStudio(IntelliJ) でのテンプレート

#if (${PACKAGE_NAME} && ${PACKAGE_NAME} != "")package ${PACKAGE_NAME};#end

import android.support.v4.app.Fragment;
import android.os.Bundle;

#parse("File Header.java")
public class ${NAME} extends Fragment {
    public static final String TAG = ${NAME}.class.getSimpleName();

    public static ${NAME} newInstance() {
        ${NAME} fragment = new ${NAME}();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }
}
53
53
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
53