Created
July 16, 2015 09:17
-
-
Save fkmhrk/63a62ecbc8152af12ef7 to your computer and use it in GitHub Desktop.
Activityと(Dialog)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 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