Skip to content

Instantly share code, notes, and snippets.

@fkmhrk
Created July 16, 2015 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fkmhrk/63a62ecbc8152af12ef7 to your computer and use it in GitHub Desktop.
Save fkmhrk/63a62ecbc8152af12ef7 to your computer and use it in GitHub Desktop.
Activityと(Dialog)Fragmentの連携をどうやるか
public class DemoDialogFragment extends DialogFragment {
public static DialogFragment newInstance(int requestCode) {
DialogFragment dialog = new DemoDialogFragment();
Bundle args = new Bundle();
args.putBoolean(ARGS_CALLER_ACTIVITY, true);
args.putInt(ARGS_REQUEST_CODE, requestCode);
dialog.setArguments(args);
return dialog;
}
public static DialogFragment newInstance(Fragment target, int requestCode) {
DialogFragment dialog = new DemoDialogFragment();
dialog.setTargetFragment(target, requestCode);
Bundle args = new Bundle();
args.putBoolean(ARGS_CALLER_ACTIVITY, false);
dialog.setArguments(args);
return dialog;
}
// 中略
// ダイアログでOKが押された時にこれが呼ばれるとする
void submit() {
Bundle args = getArguments();
boolean isCallerActivity = args.getBoolean(ARGS_CALLER_ACTIVITY);
if (isCallerActivity) {
int requestCode = args.getInt(ARGS_REQUEST_CODE);
MyActivity activity = getActivity();
if (activity == null) { return; }
activity.onDialogResult(requestCode); // なんらかのメソッドで結果を伝える
} else {
Fragment target = getTargetFragment();
if (target == null) { return; }
target.onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment