自分の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;
}
}