Android:禁用DialogFragment的“确定/取消”按钮

15

当使用AlertDialog创建DialogFragment时,我该如何禁用确认/取消按钮?我尝试调用myAlertDialogFragment.getDialog(),但它总是返回null,即使片段已经显示。

public static class MyAlertDialogFragment extends DialogFragment {

    public static MyAlertDialogFragment newInstance(int title) {
        MyAlertDialogFragment frag = new MyAlertDialogFragment();
        Bundle args = new Bundle();
        args.putInt("title", title);
        frag.setArguments(args);
        return frag;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        int title = getArguments().getInt("title");

        return new AlertDialog.Builder(getActivity())
                .setIcon(R.drawable.alert_dialog_icon)
                .setTitle(title)
                .setPositiveButton(R.string.alert_dialog_ok,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((FragmentAlertDialog)getActivity()).doPositiveClick();
                        }
                    }
                )
                .setNegativeButton(R.string.alert_dialog_cancel,
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            ((FragmentAlertDialog)getActivity()).doNegativeClick();
                        }
                    }
                )
                .create();
    }
}

我知道可以通过膨胀一个包含取消和确定按钮的布局来实现,但如果可能的话,我更愿意使用AlertDialog解决方案。

2个回答

31

您需要在DialogFragment中重写onStart()方法并保留按钮的引用。然后,您可以使用该引用稍后重新启用该按钮:

Button positiveButton;

@Override
public void onStart() {
    super.onStart();
    AlertDialog d = (AlertDialog) getDialog();
    if (d != null) {
        positiveButton = d.getButton(Dialog.BUTTON_POSITIVE);
        positiveButton.setEnabled(false);
    }

}

1
很棒的答案!无论如何,您不必将d.getButton的返回值转换为Button对象。 - Guillermo Barreiro
可以了,不需要转换类型:positiveButton = d.getButton(Dialog.BUTTON_POSITIVE); 就足够了。 - Andrew

29

将您的AlertDialog附加到变量中:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
(initialization of your dialog)
AlertDialog alert = builder.create();
alert.show();

然后从您的AlertDialog中获取按钮并设置其禁用/启用状态:

Button buttonNo = alert.getButton(AlertDialog.BUTTON_NEGATIVE);
buttonNo.setEnabled(false);

它给你在运行时更改按钮属性的机会。

然后返回您的警报变量。

AlertDialog必须在获取其视图之前显示。


3
我尝试了,但不起作用,因为在 alert.show() 之前调用 alert.getButton(AlertDialog.BUTTON_NEGATIVE); 将返回 null。因此我不知道应该在哪里调用它... - user1026605
8
可以的(我个人觉得这很烦人)。你想要做的是在生命周期后面的某个时刻调用setEnabled()方法,可能是在onResume()之后。 - Delyan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接