我有一个ListFragment
,其中包含我ListItem
的上下文菜单。其中一个菜单选项是删除项目,我想向用户显示一个确认对话框,以防止意外删除。
public class MyListFragment extends ListFragment implements ConfirmDeletePopupFragment.DialogListener {
(...)
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
ConfirmDeletePopupFragment fragment = new ConfirmDeletePopupFragment();
fragment.show(getSupportFragmentManager(), "tag");
return true;
case R.id.action_cancel:
return true;
default:
return super.onContextItemSelected(item);
}
}
}
对于类似情况,我创建了一个通用确认对话框,如下所示DialogFragment
。我可以用它来让用户确认任何关键动作。要在Activity
中使用,它有一个方法onDeleteConfirm
的接口,用于处理创建对话框的Activity
中的实际删除。
public class ConfirmDeletePopupFragment extends DialogFragment {
(...)
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mDialogListener = (DialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(getTargetFragment().toString() + " must implement ConfirmDeletePopupFragment.DialogListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final android.app.AlertDialog.Builder dialogBuilder = new android.app.AlertDialog.Builder(getActivity());
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.popup_confirm_delete, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Delete?");
dialogBuilder.setNegativeButton(getString(R.string.activities_confirm_deletion_cancel_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
dialogBuilder.setPositiveButton(getString(R.string.activities_confirm_deletion_delete_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((DialogListener) getActivity()).onDeleteConfirm();
}
});
deleteDialog = dialogBuilder.create();
deleteDialog.show();
return deleteDialog;
}
public interface DialogListener {
void onDeleteConfirm();
}
}
显然,只有在Activity
(((DialogListener) getActivity()).onDeleteConfirm();
)中创建对话框时,此界面才有效。对于上面提到的问题,我需要在Listfragment
内创建对话框,只需在ListFragment
中实现对话框界面不起作用(“Activity必须实现ConfirmDeletePopupFragment.DialogListener”)
调整DialogFragment
的最佳方法是什么,以便适应两种情况(在Activity
或Fragment
中创建)?
答案 0 :(得分:3)
显示对话框(片段中)时:
<dialog>.setTargetFragment(<your fragment>);
<dialog>.show();
在活动中跳过setTargetFragment。
在DialogFragment代码中:
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (getTargetFragment() != null) {
myInterface = (YourCastInterface) getTargetFragment();
} else {
myInterface = (YourCastInterface) activity;
}
}