Android implements the method of not closing the dialog box when clicking a button on AlertDialog

  • 2020-06-15 10:10:02
  • OfStack

This article illustrates Android's method of not closing the dialog box when clicking a button on AlertDialog. Share to everybody for everybody reference. The details are as follows:

During development, there are sometimes requirements such as:

Clicking a button displays a dialog box with an input box and two buttons for "Ok" and "Cancel". When the user clicks the ok button, the content of the input box needs to be judged. Do not close the dialog box if the content is empty, and toast prompts.

When creating a dialog box using AlertDialog.Builder, you can use the builder.setNegativeButton and builder.setPositiveButton methods to set the click event for the cancel button and the confirm button. The problem, however, is that as soon as the user clicks the ok or cancel button, the system automatically closes the dialog.

The solution to this problem is:

(1) Use builder. setPositiveButton to set the text of the confirmation button, but do not add listening. That is:

builder.setPositiveButton(R.string.main_ok, null);

(2) AlertDialog object:

AlertDialog alertDialog = builder.create();  
alertDialog.show();

(3) Get the confirmation button on the dialog box, and then add ordinary ES29en.OnClickListener to the button. alertDialog.dismiss () is called manually to close the dialog once the user has entered it correctly.
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 the number ");
     return;
 }  // send
 sendProfile(cardNum);
 alertDialog.dismiss();
    }
});

The problem was solved perfectly.

I hope this article has been helpful for your Android programming.


Related articles: