我遇到了一些障碍。我有一个非常类似于描述的场景:DialogFragment - 在屏幕旋转后保留侦听器
建议的解决方案对作者来说很好,因为他的对话是从一个活动中调用的。我的情况完全相同,但我的自定义对话框是从片段而不是活动中调用的。(IE活动->片段->对话框)
我实现了相同的解决方案(在调用片段的 onResume 中设置监听器),但在这种情况下它不起作用。
似乎正在发生的是,当屏幕旋转时,Android 会杀死 Dialog 和 Fragment。然后按该顺序重新创建它们。因此,当在我的自定义对话框上调用我的 onCreateDialog 时,包含的 Fragment 尚未重新创建,因此侦听器为正按钮和负按钮设置 null 。
有谁知道解决这个问题的方法?
public class RecipeDetailEditFragment extends SherlockFragment implements DialogInterface.OnClickListener {
private EditStepFragmentDialog stepDialog;
private Recipe newRecipe; //main data object implements parcelable
...
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
stepDialog = EditStepFragmentDialog.newInstance(newRecipe);
//I've also tried passing 'this' into the newInstance constructor and
//setting the listener there, but that doesn't work either
}
public void onResume() {
stepDialog.setListener(this);
super.onResume();
}
...
}
public class EditStepFragmentDialog extends DialogFragment {
private DialogInterface.OnClickListener ocl;
private static final String ARG_RECIPE = "recipe";
private Recipe recipe;
public EditStepFragmentDialog() {}
public static EditStepFragmentDialog newInstance(Recipe rec) { //(Recipe rec, DialogInterface.OnClickListener oc) as mentioned doesn't work.
EditStepFragmentDialog dia = new EditStepFragmentDialog();
Bundle args = new Bundle();
args.putParcelable(ARG_RECIPE, rec);
//dia.setListener(oc);
return dia;
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder adb = new AlertDialog.Builder(getActivity());
if (getArguments().containsKey(ARG_RECIPE)) {
recipe = (Recipe) getArguments().getParcelable(ARG_RECIPE);
}
...
adb.setPositiveButton("Done", ocl);
adb.setNegativeButton("Cancel", ocl);
...
return adb.create();
}
public void setListener(DialogInterface.OnClickListener cl) {
ocl = cl;
}
}