Dave Dave - 2 months ago 15
Android Question

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

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..

Answer

Build a custom dialog with a EditText with the attribute android:password="true" a button, then manually set onClick listener the button, and explicitly choose what to do in it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical">

    <EditText 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:minWidth="180dip" 
        android:digits="1234567890" 
        android:maxLength="4" 
        android:password="true"/>

    <LinearLayout 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:orientation="horizontal">

        <Button 
            android:id="@+id/Accept" 
            android:layout_width="fill_parent" 
            android:layout_height="wrap_content" 
            android:text="Accept"/>

    </LinearLayout> 
</LinearLayout> 

Then when you want it to pop up:

final Dialog dialog = new Dialog(RealizarPago.this);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("PIN number:");
dialog.setCancelable(true);

Button button = (Button) dialog.findViewById(R.id.Accept);
button.setOnClickListener(new OnClickListener() {
@Override
    public void onClick(View v) {
        if(password_wrong){ 
          // showToast
        } else{
          dialog.dismiss();
          // other stuff to do
        }
    }
}); 

dialog.show();