还有另一种方法可以从 DialogFragment 中获取结果。
您可以使用Fragment.setTargetFragment()。创建 DialogFragment 的实例时,将目标片段设置为它。然后在 DialogFragment 中,您可以从Fragment.getTargetFragment()获取此片段。
例如,您可以这样做:
public interface DialogClickListener {
public void onYesClick();
public void onNoClick();
}
public class MyListFragment extends ListFragment implements DialogClickListener {
...
private void showDialog() {
DialogFragment dialog = new MyDialogFragment();
dialog.setTargetFragment(this, 0);
dialog.show(getFragmentManager(), "dialog");
}
@Override
public void onYesClick() {
// do something
}
@Override
public void onNoClick() {
// do something
}
}
public class MyDialogFragment extends DialogFragment {
private DialogClickListener callback;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
callback = (DialogClickListener) getTargetFragment();
} catch (ClassCastException e) {
throw new ClassCastException("Calling fragment must implement DialogClickListener interface");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("message")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onYesClick();
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
callback.onNoClick();
}
});
return builder.create();
}
}