During the development process, there are times when this is required:
After clicking on a button, a dialog box is displayed with an input box above it, and there are two buttons for "Confirm" and "Cancel". When the user clicks on the confirmation button, the content of the input box needs to be judged. If the content is empty, the dialog box is not closed, and the toast prompt.
When you create a dialog box using Alertdialog.builder, you can use the Builder.setnegativebutton and Builder.setpositivebutton two methods to set the Cancel button and the Confirm button's Click event. The problem, however, is that the dialog box is automatically closed as long as the user clicks the Confirm button or the Cancel button.
The workaround for this problem is:
(1) Use Builder.setpositivebutton to set the text of the confirmation button, but do not add listening. i.e. Builder.setpositivebutton (R.STRING.MAIN_OK, NULL);
(2) Get Alertdialog object:
Alertdialog Alertdialog = Builder.create (); Alertdialog.show ();
(3) Get the Confirmation button on the dialog box and add a normal view.onclicklistener to the button. Manually call Alertdialog.dismiss () to close the dialog box when the user enters the correct input.
Alertdialog.getbutton (alertdialog.button_positive). Setonclicklistener (New View.onclicklistener () { @Override Public void OnClick (View v) { String cardnum = Cardnumet.gettext (). toString (). Trim (); if (cardnum.length () = = 0) { utility.showtoast (mactivity, "Please enter Number"); return; } Send Sendprofile (cardnum); Alertdialog.dismiss (); } });
Problem solved perfectly.
Android: Implementation Click on the Alertdialog button when the dialog box is not closed