Android: the dialog box is not closed when you click the AlertDialog button.
In the development process, there are sometimes such requirements:
After clicking a button, a dialog box is displayed. the dialog box contains an input box and two buttons, "OK" and "cancel", are displayed. When you click the OK button, you need to determine the content of the input box. If the content is blank, the dialog box is not closed and the toast prompt is displayed.
When creating a dialog box using AlertDialog. Builder, you can use builder. setNegativeButton and builder. setPositiveButton to set click events for the cancel button and confirmation button. However, the system automatically closes the dialog box when you click the OK or cancel button.
The solution to this problem is:
(1) Use builder. setPositiveButton to set the text of the confirmation button, but do not add a listener. That is, builder. setPositiveButton (R. string. main_ OK, null );
(2) obtain the AlertDialog object:
AlertDialog alertDialog = builder.create();alertDialog.show();
(3) obtain the confirmation button in the dialog box, and then add a common View. OnClickListener to the button. When the user inputs the correct information, manually call alertDialog. dismiss () to close the dialog box.
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, "Enter the number"); return ;}// send sendProfile (cardNum); alertDialog. dismiss ();}});
The problem is solved perfectly.