Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop AlertDialog from closing on positive button click

Tags:

android

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();
like image 435
TMH Avatar asked Jun 16 '14 12:06

TMH


1 Answers

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();
            }
        });
    }
});
like image 88
prabhakaran Avatar answered Nov 08 '22 22:11

prabhakaran