How to disable / enable dialog negative positive buttons?

前端 未结 7 1158
太阳男子
太阳男子 2020-11-28 23:30

Please look at the custom dialog below. I have an edittext field on the dialog and if the text field is empty I would like to disable the positiveButton. I can

相关标签:
7条回答
  • 2020-11-29 00:08

    Here is complete code to enable and disable positive button of dialog:

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflater = MainActivity.this.getLayoutInflater();
    View view = layoutInflater.inflate(R.layout.dialog,null);
    
    builder.setView(view);
    builder.setTitle("Test");
    builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this, "Ok clicked", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        }
    });
    builder.setNegativeButton("cancel", null);
    
    final AlertDialog alertDialog = builder.create();
    
    alertDialog.show();
    
    EditText editText = (EditText)view.findViewById(R.id.mobile_number);
    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
    
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {}
    
        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() >= 1) {
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
            } else {
                alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    
            }
        }
    });
    
    0 讨论(0)
提交回复
热议问题