How to keep an alertdialog open after button onclick is fired?

Viewed 35714

The subject kinda says it all.. I'm requesting a PIN code from the user, if they enter it, click the OK Positive Button and the PIN is incorrect I want to display a Toast but keep the dialog open. At the moment it closes automatically.. Sure this is very trivial thing to correct but can't find the answer yet.

Thanks..

6 Answers

You can set an OnClickListener as follows to keep the dialog open:

public class MyDialog extends AlertDialog {
    public MyDialog(Context context) {
        super(context);
        setMessage("Hello");
        setButton(AlertDialog.BUTTON_POSITIVE, "Ok", (new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // this will never be called
            }
        });
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ok) {
                    // do something
                    dismiss();
                } else {
                    Toast.makeText(getContext(), "when you see this message, the dialog should stay open", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

Same problem for me in a FragmentDialog. Here's my criminal/elegant solution: Remove all buttons from the dialog (positive,negative,neutral). Add your buttons from the xml.eg.:

<LinearLayout
        android:layout_width="match_parent"
        android:orientation="horizontal"
        android:layout_height="wrap_content">
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/button_cancel"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:text="@android:string/cancel"
            android:layout_gravity="left"
            />
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/button_ok"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:text="@android:string/ok"
            android:layout_gravity="right"
            />
    </LinearLayout>

And then in your code handle it with:

view.findViewById(R.id.button_ok).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view2) {
                    if (wannaClose)
                        dismiss();
                    else
                        //do stuff without closing!
                }
            });

where view is the view assigned to the dialog!

Related