1

I would like to retrieve user input via an Alert Dialog... is there any way to make it so that the user cannot press Ok if the EditText is blank? I mean require that he type something in?

ycomp
  • 8,316
  • 19
  • 57
  • 95

2 Answers2

4

you can use textchangeListener to achieve this in afterTextChange method check text of editText, and according to length set enable or disable Ok button, as follows:

editText.addTextChangedListener(new TextWatcher() {
                        public void afterTextChanged(Editable s) {
                                //XXX do something
                                if(editText.getText().length()>0)
                                     btnOk.setEnabled(true);
                                else
                                     btnOk.setEnabled(false);
                        }
                        public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
                                //XXX do something
                        }
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                            //XXX do something
                    }
    }); 
jeet
  • 29,001
  • 6
  • 52
  • 53
  • this requires a custom layout? or is there a way to access the AlertDialog default ok button? – ycomp Feb 21 '12 at 04:54
  • you can do with dialog's default button also: alertDialog.getButton(whichButton).setEnabled(enabled); – jeet Feb 21 '12 at 05:00
  • **for future readers:** there is a problem getButton() returns null in API 7 (fixed in 2.2) before show() is called. Solution call show() first... http://goo.gl/amxhY , http://goo.gl/UbGNg – ycomp Feb 22 '12 at 14:40
1

use customized layout for alert dialog. ex:

Dialog dialog = new Dialog(this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);

            dialog.setContentView(R.layout.your_layout_name);
            //sample for getting view id...

            //TextView dialogbody=(TextView) dialog.findViewById(R.id.dialogbody);
Venkata Krishna
  • 1,543
  • 1
  • 11
  • 19