Android: Implementation Click on the Alertdialog button when the dialog box is not closed

Source: Internet
Author: User

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

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.