Android: the dialog box is not closed when you click the AlertDialog button.

Source: Internet
Author: User

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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.