Подтвердить что ты не робот

Как сохранить alertdialog открытым после нажатия кнопки onclick?

Тема kinda говорит все это. Я запрашиваю у пользователя PIN-код, если они его вводят, нажмите кнопку OK Positive и неверный PIN-код. Я хочу отобразить Toast, но не открывайте диалог. В настоящий момент он автоматически закрывается. Конечно, это очень тривиально, но вы не можете найти ответ.

Спасибо..

4b9b3361

Ответ 1

Создайте настраиваемый диалог с помощью EditText с атрибутом android: password = "true" a, затем вручную установите onClick listener кнопку и явно выберите, что делать в ней.

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

Затем, когда вы хотите, чтобы он всплывал:

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();  

Ответ 2

Вам не нужно создавать пользовательский класс. Вы можете зарегистрировать View.OnClickListener для AlertDialog. Этот слушатель не отклонит AlertDialog. Трюк здесь заключается в том, что вам нужно зарегистрировать слушателя после того, как было показано диалоговое окно, но его можно аккуратно выполнить внутри OnShowListener. Вы можете использовать вспомогательную логическую переменную, чтобы проверить, было ли это уже сделано, чтобы она выполнялась только один раз:

    /*
     * Prepare the alert with a Builder.
     */
    AlertDialog.Builder b = new AlertDialog.Builder(this);

    b.setNegativeButton("Button", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {}
    });
    this.alert = b.create();

    /*
     * Add an OnShowListener to change the OnClickListener on the
     * first time the alert is shown. Calling getButton() before
     * the alert is shown will return null. Then use a regular
     * View.OnClickListener for the button, which will not 
     * dismiss the AlertDialog after it has been called.
     */

    this.alertReady = false;
    alert.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface dialog) {
            if (alertReady == false) {
                Button button = alert.getButton(DialogInterface.BUTTON_NEGATIVE);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //do something
                    }
                });
                alertReady = true;
            }
        }
    });

Часть этого решения была предоставлена ​​http://groups.google.com/group/android-developers/browse_thread/thread/fb56c8721b850124#

Ответ 3

Вы можете установить OnClickListener следующим образом, чтобы открыть диалоговое окно:

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();
                }
            }
        });
    }
}

Ответ 4

Вы можете просто продолжить использование уже имеющегося диалога, просто поместите предложение if в onClick(), говоря

if(pin_check_method){  //pin_check_method should be a boolean returned method
     //close the Dialog, then continue
     }
   else{
     //dont put the dialog.dismiss() in here, put instead
    Toast.makeText(getApplicationContext(),"Invalid pin, please try again",Toast.LENGTH_LONG).show();
}

Теперь, чтобы использовать этот код, просто вызовите text.setText(""); и введите текст, который вы хотите здесь общая ошибка заключается в том, что при вводе:

TextView text = (TextView) findViewById(R.id.dialog);

вы пропустите, что он действительно должен быть

dialog.findViewById

и это независимо от того, что имя диалогового окна, в моем примере это просто одноименное имя.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/layout_root" 
                android:layout_width="fill_parent" 
                android:layout_height="fill_parent" 
                >

    <TextView android:id="@+id/text"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              android:layout_centerHorizontal="true"
              android:layout_width="wrap_content"/>



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

</RelativeLayout>

Ответ 5

Такая же проблема для меня в FragmentDialog. Здесь мое криминальное/элегантное решение: Удалите все кнопки из диалога (положительные, отрицательные, нейтральные). Добавьте свои кнопки из 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>

И затем в вашем коде обрабатывайте его с помощью:

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

где view - это представление, назначенное диалогу!