繁体   English   中英

带有DialogFragment的Android AlertDialog:即使单击“确定”,也不要关闭对话框

[英]Android AlertDialog with DialogFragment: don't close the dialog even if OK is clicked

我有一个自定义布局的AlertDialog(只是一个EditText),我想在单击确定按钮时验证数据。 如果验证失败,我不想关闭对话框。

我正在使用对话框的默认按钮(正面和负面)。 如果我使用“setPositiveButton(”“,new DialogInterface.OnClickListener()...”对话框总是关闭的。我看过几个帖子,他们说onClick Listener应该被覆盖,但我不能让它工作这是我发现的代码:

Button theButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
theButton.setOnClickListener(new CustomListener(dialog));

因为它说它应该在显示对话框之后完成,所以我把这个代码放在我的活动中,而不是在我的DialogFragment中,但是如果我使用mDialogFragment.getDialog()它总是返回null。

这是我的Dialog片段的一部分:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    builder.setTitle(R.string.new);

    LayoutInflater inflater = getActivity().getLayoutInflater();
    dialogView = inflater.inflate(R.layout.edit_license, null);

    builder.setView(dialogView)

    // Add action buttons
    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {

        }
    })
    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            MyDialogFragment.this.getDialog().cancel();
        }
    }); 

    return builder.create();

}

在我的活动中,我执行以下操作:

DialogFragment dialog = new MyDialogFragment(true, null);
dialog.show(getSupportFragmentManager(), "EditLicenseDialogFragment");

AlertDialog alertDialog = (AlertDialog)dialog.getDialog();
alertDialog.getButton(DialogInterface.BUTTON_POSITIVE);
btnPositive.setOnClickListener(new CustomListener(alertDialog));

... 

class CustomListener implements View.OnClickListener {
    private final Dialog dialog;
    public CustomListener(Dialog dialog) {
        this.dialog = dialog;
    }
    @Override
    public void onClick(View v) {
        ...
    }
}

就像我说的,(AlertDialog)dialog.getDialog(); 始终返回null。 这是为什么? 如果验证不正确,如何避免关闭对话框?

谢谢!

这个解决方案适合我。 对话框已在onResume中可见,因此这是一个访问按钮和替换侦听器的好地方。

public class XYZFragment extends DialogFragment {
   ...

    @Override
    public void onResume() {
        super.onResume();

        AlertDialog dialog = (AlertDialog)getDialog();

        Button positiveButton = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
        positiveButton.setOnClickListener(new View.OnClickListener() {                  
            @Override
            public void onClick(View onClick) {
            ...
            }
        });
    }
}

这里是DialogFragment引用的一些文本:

显示对话框窗口的片段,浮动在其活动窗口的顶部。 该片段包含一个Dialog对象,它根据片段的状态适当显示。 控制对话框 (决定何时显示,隐藏,关闭它) 应该通过API在这里完成,而不是直接调用对话框。

而不是调用getDialog()。dismiss()你应该做dismiss()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM