在AlertDialog中禁用正按钮

时间:2017-01-08 19:01:17

标签: 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();
    }
   }

3 个答案:

答案 0 :(得分:0)

在正按钮监听器上验证数据,如果数据有效,则继续进行,如果没有显示有关错误的祝酒词。

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我使用了不同的方法来完成这项工作。希望能为人们省去麻烦。我在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();
}