0

I have a EditText within a AlertDialog. I want to dismiss it only when the EditText has some input in it otherwise show a Toast prompting the user to enter the data.

Currently, when the edit text has data the dialog dismissed properly. Also when the edittext is blank the toast is shown. However the dialog still dismisses even if the EditText is empty and the Toast message is shown later.

I dont want the ALertDialog to dismiss and EditText should gain focus again after the Toast is shown.

Here is my code:-

builder.setPositiveButton("Post", new DialogInterface.OnClickListener()
            {

                public void onClick(DialogInterface dialog, int id) 
                {

                    boolean worked = true;
                    postedComment = input1.getText().toString();

                    if(postedComment.length()==0 || postedComment=="" || postedComment.matches(""))
                    {

                        Toast.makeText(NewsDetails.this, "Please enter a comment.", Toast.LENGTH_LONG).show();
                        input1.findFocus();
                        worked = false;
                    }
                    else if(worked && postedComment!="")
                    {

                        dialog.dismiss();
                        pd = new ProgressDialog(NewsDetails.this);
                        pd.setMessage("Posting..");
                        pd.show();
                        pd.setCancelable(true);

                        PostComments(postedComment);
                    }
                }) 
.setCancelable(false);

            alert = builder.create();
            alert.setCanceledOnTouchOutside(true);

            alert.show();
user3146095
  • 419
  • 2
  • 7
  • 25
  • 4
    you need to use custom dialog rather alert.Because you don't have control after button click. That is after button click it will dismiss by default. – Biraj Zalavadia Jul 16 '14 at 04:28
  • @Biraj Can you please direct me to a example that might serve my purpose – user3146095 Jul 16 '14 at 04:32
  • Also, you should be using the `equals()` method to compare Strings, instead of like this: `postedComment==""`. In your case the `TextUtils.isEmpty()` method would be of use, too. – Mike M. Jul 16 '14 at 04:38
  • http://stackoverflow.com/questions/13341560/how-to-create-a-custom-dialog-box-in-android – Biraj Zalavadia Jul 16 '14 at 04:39
  • See below link may be helpful for you http://stackoverflow.com/questions/2620444/how-to-prevent-a-dialog-from-closing-when-a-button-is-clicked – Umesh Lakhani Jul 16 '14 at 04:40
  • pd.setCancelable(false); add this line in following condition if(postedComment.length()==0 || postedComment=="" || postedComment.matches("")){} – MFP Jul 16 '14 at 04:59

1 Answers1

0

You need to write custom dialog for your requirement. see Custom Dialog with Edit Text

Sunil Kumar Sahoo
  • 53,011
  • 55
  • 178
  • 243