How to disable / enable dialog negative positive buttons?

前端 未结 7 1250
太阳男子
太阳男子 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-28 23:56

    None of these answers really solve the problem.

    I accomplish this using a custom layout with an EditText in it and a TextWatcher on that view.

    final LinearLayout layout = (LinearLayout) inflator.inflate(R.layout.text_dialog, null);
    final EditText text = (EditText) layout.findViewById(R.id.text_edit);
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setView(layout);
    // Now add the buttons...
    builder.setPositiveButton(R.string.ok, new AlertDialog.OnClickListener() {
        // Left out for brevity...
    }
    builder.setNegativeButton(R.string.cancel, new AlertDialog.OnClickListener() {
        // Left out for brevity...
    }
    
    // Create the dialog
    final AlertDialog d = builder.create();
    
    // Now add a TextWatcher that will handle enable/disable of save button
    text.addTextChangedListener(new TextWatcher() {
        private void handleText() {
            // Grab the button
            final Button okButton = d.getButton(AlertDialog.BUTTON_POSITIVE);
            if(text.getText().length() == 0) {
                okButton.setEnabled(false);
            } else {
                okButton.setEnabled(true);
            }
        }
        @Override
        public void afterTextChanged(Editable arg0) {
            handleText();
        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // Nothing to do
        }
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
           // Nothing to do
        }
    });
    
    // show the dialog
    d.show();
    // and disable the button to start with
    d.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    

提交回复
热议问题