Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.