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

时间:2013-04-09 20:43:25

标签: android button alertdialog dialogfragment

如何在使用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 个答案:

答案 0 :(得分:25)

将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。

答案 1 :(得分:25)

您需要在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);
    }

}