android - 在 AlertDialog 中禁用肯定按钮

标签 android android-alertdialog

我已经查看了 stackoverflow 上的大部分帖子,但我无法正常工作。除非所有字段都已完成,否则我希望禁用肯定按钮(注册)。

我怎样才能做到这一点?

public static class UsernameDialogFragment extends DialogFragment {


    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        LayoutInflater inflater = getActivity().getLayoutInflater();


        builder.setView(inflater.inflate(R.layout.ipcamaccount, null))
                .setPositiveButton(R.string.action_register, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialog, int id) {

                       //some other code
                        }
                    }
                });

        builder.setView(inflater.inflate(R.layout.ipcamaccount, null))
                .setNegativeButton(R.string.action_cancel, null);


        return builder.create();
    }
   }

最佳答案

我使用了不同的方法来完成这项工作。希望它能为某人省去麻烦。我在 RecyclerView 适配器中使用它,因此您必须设置上下文。我不知道这是否是最优雅的方式,但它工作得很好。

代码如下:

private void myDialog() {

    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
    dialogBuilder.setView(R.layout.ipcamaccount);

    dialogBuilder.setPositiveButton(R.string.action_register, null);
    dialogBuilder.setNegativeButton(R.string.action_cancel, null);

    final AlertDialog alertDialog = dialogBuilder.create();
    alertDialog.show();

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

            onPositiveButtonClicked(alertDialog);
        }
    });

    Button negativeButton = alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE);

    negativeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNegativeButtonClicked(alertDialog);
        }
    });
}

private void onPositiveButtonClicked(AlertDialog alertDialog) {

      if(some condition) {

       alertDialog.dismiss();

        Toast.makeText(mContext, "Some toast", Toast.LENGTH_LONG).show();

    }else {
        Toast.makeText(mContext, "Some other toast", Toast.LENGTH_LONG).show();
    }

}

private void onNegativeButtonClicked(AlertDialog alertDialog) {
    alertDialog.dismiss();
}

关于android - 在 AlertDialog 中禁用肯定按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41536599/

相关文章:

java - alertdialog - removeView 必须被调用

android - RecyclerView 适配器中的 LayoutInflater

android - Dagger 2 创建单例实例

android - 通过 webview saveWebArchive 获取 webArchive

android - 单击按钮 "Yes"时如何关闭警报

java - 如何以编程方式关闭Android中的对话框?

ICS 和 Gingerbread 上的 Android 自定义警报对话框不同

java - 无法从 QuickAction 打开 AlertDialog

Android 从 Intent 获取 vCard 数据

Android:使用 drawText() 书写时文本不可见