TMH
TMH

Reputation: 6246

Stop AlertDialog from closing on positive button click

I'm trying to setup a custom AlertDialog, which has 2 buttons, cancel and a positive button. I need to make it so what the positive button is clicked, I can change the text, and not have the dialog close.

Rough flow is the positive button will say "Send", when it's clicked it will change to "Sending...", then the code will send some data to our server, and if the response is true, close the dialog, if it's false, or timeouts etc show an error message (Toast) and keep the dialog open.

I have code for sending data to the server, handling responses etc, I just can't think how to edit the AlertDialog class implement this. Does anyone know how I'd go about doing this?

Current testing code:

AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
b.setView(getActivity().getLayoutInflater().inflate(R.layout.dialog_single_text, null));
b.setTitle("Forgotten Password");
b.setMessage("Please enter your email");
b.setPositiveButton("Send", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getActivity(), "Sending...", Toast.LENGTH_SHORT).show();
    }
});
b.create().show();

Upvotes: 5

Views: 8381

Answers (2)

prabhakaran
prabhakaran

Reputation: 678

you can add an onShowListener to the AlertDialog

 d.setOnShowListener(new DialogInterface.OnShowListener() {

    @Override
    public void onShow(DialogInterface dialog) {

        Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                // TODO Do something

                //Dismiss once everything is OK.
                d.dismiss();
            }
        });
    }
});

Upvotes: 8

CodeWarrior
CodeWarrior

Reputation: 5176

There are two approaches to accomplish this

  1. Use custom dialog by using Dialog API provided by android LINK
  2. For AlertDialog you will need to override it as explained on this LINK

Upvotes: 0

Related Questions