LoginSignup
3
0

More than 3 years have passed since last update.

本当にAndroidのFragmentには空のコンストラクタが必要なの?

Posted at

フラグメントに空のコンストラクタがなぜ必要なのかを、とっさに説明できなかったので、簡単にまとめてみた。

空のコンストラクタを作成しないとどうなるか

あなたが複数の引数をとるコンストラクタを持つFragmentを作ったとする。
そのFragmentは正常に動くだろう。
その後あなたはアプリをリリースする。

その後以下のエラーメッセージ付きのクラッシュ報告がたくさん上がってくる。
開発時はエラーなんて吐かなかったのに、古いAndroidを使い続けるユーザーが悪いんだとあなたはは思いつつエラー対応に当たることになる。

Unable to instantiate fragment 
make sure class name exists, is public, and has an empty constructor that is public

fuck you android(これは本当にそう)

正しい空のコンストラクタの作り方

とにかくFragment内部のコンストラクタをoverrideするのは止める。
常に空のコンストラクタを記述し、Fragment初期化時に引数を渡したい時のために
newInstanceメソッドを作成するのが良いだろう。


public static final MyFragment newInstance(int title, String message){
  MyFragment f = new MyFragment();
  Bundle bel = new Bundle(2);
  bdl.putInt(EXTRA_TITLE, title);
  bel.putString(EXTRA_MESSAGE, message);
  f.setArguments(bel);
  return f;
}

そしてFragment内では以下のようにargumentを使用する。


@Override
public void onCreate(Bundle savedInstanceState) {
  title.= getArguments().getInt(EXTRA_TITLE);
  message = getArguments().getString(EXTRA_MESSAGE);
}

作成したFragmentは以下のように使用する。


getSupportFragmentManager()
  .beginTransaction()
  .replace(R.id.content, MyFragment.newInstance(
  R.string.alert_title,
  Oh no, an error occurred””
  ))
  .commit();

参考

3
0
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
3
0