DialogFragment になにか渡したいときは Fragment の特徴である DialogFragment#setArguments() で渡さないといけない。でもリスナー渡したいときは一筋縄ではいかない。DialogFragment#setOnDoSomethingListener() なんかを生やしても大人の事情でダメ。ここでこうやってみる。
まずはなんにせよ Listener を作る。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConfirmDialogFragment extends DialogFragment { | |
public interface OnButtonClickListener { | |
public void onPositiveClick(); | |
public void onNegativeClick(); | |
} | |
} |
こんな感じ。
Activity に通知する場合。
Activity にリスナーを implements するの忘れない。Dialog 側は onAttach(Activity activity) をオーバーライドする。ライフサイクルに組み込まれてるこのメソッドでは Activity が渡されるので、そのアクティビティが Listener を implements してるかチェックできる。なので DialogFragment#setArguments() で渡さなくてもいい。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// DialogFragment | |
@Override | |
public void onAttach(Activity activity) { | |
super.onAttach(activity); | |
try { | |
this.mOnDialogButtonClickListener = (OnDialogButtonClickListener)activity; | |
} catch (ClassCastException e) { | |
e.printStackTrace(); | |
} | |
} |
こんな感じ。あとは必要なところでthis.mOnDialogButtonClickListenerのメソッド使えばいい。
Fragment に通知する場合。
DialogFragment にいつもの newInstance() を生やす。ここで引数に Fragment をとるようにして、DialogFragment#setTargetFragment() を使って Fragment を保持。必要なときに DialogFragment#getTargetFragment() から Fragment を取ってきてリスナーにキャストして使う。ちょっと回りくどい。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ConfirmDialogFragment extends DialogFragment implements | |
DialogInterface.OnClickListener { | |
public interface OnDialogButtonClickListener { | |
public void onPositiveClick(); | |
public void onNegativeClick(); | |
} | |
public static ConfirmDialogFragment newInstance(Fragment fragment) { | |
ConfirmDialogFragment dialog = new ConfirmDialogFragment(); | |
dialog.setTargetFragment(fragment, 0); | |
return dialog; | |
} | |
@Override | |
public void onClick(DialogInterface dialog, int which) { | |
OnDialogButtonClickListener listener; | |
try { | |
listener = (OnDialogButtonClickListener) this.getTargetFragment(); | |
} catch (ClassCastException e) { | |
// リスナーなし | |
return; | |
} | |
switch (which) { | |
case DialogInterface.BUTTON_POSITIVE: | |
listener.onPositiveClick(); | |
break; | |
case DialogInterface.BUTTON_NEGATIVE: | |
listener.onNegativeClick(); | |
break; | |
} | |
} |
こんな感じでいいんじゃまいか。