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

use*_*605 11 android button android-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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

agi*_*llo 27

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

}
Run Code Online (Sandbox Code Playgroud)


Art*_*ski 26

将AlertDialog附加到变量:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
(initialization of your dialog)
AlertDialog alert = builder.create();
alert.show();
Run Code Online (Sandbox Code Playgroud)

然后从AlertDialog获取按钮并将其设置为禁用/启用:

Button buttonNo = alert.getButton(AlertDialog.BUTTON_NEGATIVE);
buttonNo.setEnabled(false);
Run Code Online (Sandbox Code Playgroud)

它为您提供了在运行时更改按钮属性的机会.

然后返回您的警报变量.

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

  • 它确实如此,是的(我个人觉得这很烦人).你想要做的是在生命周期的后期某处进行`setEnabled()`调用,可能是在`onResume()`之后. (8认同)
  • 我试过但它没有工作因为alert.getButton(AlertDialog.BUTTON_NEGATIVE); 在alert.show()之前调用时将返回null因此我不知道在哪里调用它... (2认同)