Cómo hacer que AlertDialog bloquee el código?

Estoy intentando mostrar un mensaje con el botón Aceptar. Estoy utilizando AlertDialog para este propósito y me di cuenta de que no está bloqueando el código. Ejemplo:

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new AlertDialog.Builder(this).setTitle("Test dlg").setMessage("Alert 1") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }) .setNegativeButton("", null) .show(); new AlertDialog.Builder(this).setTitle("Test dlg").setMessage("Alert 2") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }) .setNegativeButton("", null) .show(); //...continue with UI initialization here... } 

Cuando inicie la actividad, se muestra Alert2, Cuando presiono ok muestra Alert1 después.

Necesito tener un diálogo de código de bloqueo, por lo que al principio debe mostrar el mensaje Alert1, esperar hasta que el usuario presione el botón OK luego seguir ejecutando el código y mostrar el mensaje Alert2, etc. Ejemplo:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); msgBox("Test dlg", "Alert 1"); msgBox("Test dlg", "Alert 2"); //...continue with UI initialization here... } private void msgBox(String title, String msg){ //????? /* WRONG, NON-BLOCKING new AlertDialog.Builder(this).setTitle(title).setMessage(msg) .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }) .setNegativeButton("", null) .show(); */ } 

¿Qué debo escribir en // ????? Lugar en el método msgBox?

MÁS EJEMPLO, necesito algo como esto:

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (isInitialisationDataFailed()){ msgBox("Alert", "Cannot open activity, sorry"); myActivity.this.finish(); return; } } 

Pero esto no funciona. El acabado de la actividad se ejecuta más rápido que la alerta en la pantalla.

La idea principal de tener el código del cuadro de mensaje separado para poseer el método para hacerlo reutilizable. ¿Cómo lograrlo?

///////////////////////////////// otro ejemplo:

 private void init(){ //init code here... if (isSomethingWhrong()){ msgbox("wrong stuff will be fixed"); //do fix wrong stuff here... } if (isAnotherthingWrong()){ msgbox("more wrong stuff will be fixed"); //do fix more wrong stuff.... } //continue init code here... } private void msgbox(String msg){ //BLOCKING DIALOG REALISATION here... } 

Y como alternativa esto:

 private void init(){ //init code here... handleWrongStuff(); } private void handleWrongStuff(){ if (isSomethingWhrong()){ new AlertDialog.Builder(activity) .setTitle("Test") .setMessage("wrong stuff will be fixed") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //do fix wrong stuff here... handleMoreWrongStuff(); } }) .setNegativeButton("", null) .show(); } else{ handleMoreWrongStuff(); } } private void handleMoreWrongStuff(){ if (isAnotherthingWrong()){ new AlertDialog.Builder(activity) .setTitle("Test") .setMessage("more wrong stuff will be fixed") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //do fix more wrong stuff here... continueInit(); } }) .setNegativeButton("", null) .show(); } else{ continueInit(); } } private void continueInit(){ //continue init code here... } 

¿Ves la diferencia en la complejidad? Para hacer que el código init funcione en Android, necesito dividirlo para separar métodos pero no en bloques lógicos, pero cuando necesito mostrar diálogos. Además, el código para los diálogos de inicialización se repite y se vuelve feo e ilegible.

Ponga el código para mostrar el segundo diálogo en el botón de clic del botón positivo del cuadro de diálogo Alerta.

Utilizando de esta manera no se puede detener la ejecución, pero en lugar de esto se puede poner en el oyente botón de acción por lo que cuando el botón pulsado en ese oyente plazo se invocará y se puede ejecutar el código por ejemplo en su caso cuando presiona el botón ok luego Muestra la siguiente alerta del oyente.

  new AlertDialog.Builder(this).setTitle("Test dlg").setMessage("Alert 1") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { new AlertDialog.Builder(YourActivity.this).setTitle("Test dlg").setMessage("Alert 2") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) {} }) .setNegativeButton("", null) .show(); } }) .setNegativeButton("", null) .show(); 

Los cuadros de diálogo no bloquean la ejecución de código – bastante simple. La única manera de lograr un comportamiento de tipo "bloque" es dividir la cadena de ejecución en bits más pequeños.

Supongamos que desea mostrar un total de cinco cuadros de diálogo durante la inicialización de la interfaz de usuario. En su actividad, cree los métodos siguientes:

 private void beforeFirstDialog() { // Do the initialization until you want the first dialog // Show the first dialog // When clicking 'OK' in the first dialog, beforeSecondDialog() is called. } private void beforeSecondDialog() { // Do the initialization until you want the second dialog // Show the second dialog // When clicking 'OK' in the second dialog, beforeThirdDialog() is called. } private void beforeThirdDialog() { // Do the initialization until you want the third dialog // Show the third dialog // When clicking 'OK' in the third dialog, beforeFourthDialog() is called. } private void beforeFourthDialog() { // Do the initialization until you want the fourth dialog // Show the fourth dialog // When clicking 'OK' in the first dialog, beforeFifthDialog() is called. } private void beforeFifthDialog() { // Do the initialization until you want the fifth dialog // Show the fifth dialog // When clicking 'OK' in the first dialog, afterFifthDialog() is called. } private void afterFifthDialog() { // Do what needs to be done after the last dialog. } 

Esta es una respuesta tardía, pero puede darle cierre.

La manera más limpia de hacer lo que quieres es iniciar una actividad en lugar del diálogo . Una actividad simple con un solo botón OK.

Cuando pulse el botón OK, cierre la actividad.
Si necesita respuestas más complejas, más botones, entrada de texto, etc.
Use StartActivityWithResult () para devolver la opción del usuario

Bajo el conditon dar esto.

ShowAlert.displayAlert (el nombre actual de la clase.este, "Por favor ingrese el mensaje de error");

  strDomain.requestFocus(); 

Crear una nueva clase ShowAlert, dentro de la que poner este código.

Clase pública ShowAlert {

  public static void displayAlert(Activity act,String msg) { AlertDialog.Builder alert = new AlertDialog.Builder(act); alert.setMessage(msg).setPositiveButton("OK", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); } } 

EditText strDomain;

StrDomain es el nombre edittext. Me gusta cuando ese campo es nulo he hecho que a menos que esté lleno no va a ir a la página siguiente .. ¿cuál es su caso cuando desea mostrar el mensaje en instancia de querer?

Como usted (pudo haber) descubierto de las muchas respuestas que usted no debe bloquear el Thread Main UI . Sin embargo, si tiene una muy buena razón para bloquear el código mientras recibe una respuesta del usuario, puede crear un subproceso en el que bucle / espera la entrada del usuario mientras se muestra MainUI través del Thread MainUI . Tengo una entrada de blog completa aquí que explica esto

 protected void RunConfirmAction(Action runnableAction) { var confirmThread = new Thread(() => runnableAction()); confirmThread.Start(); } // OnClick (when the user clicks Logout Button, I call this RunConfirmAction(Logout); // the implemtation of the MessageBox waiting looks like this: public DialogResult MessageBoxShow(string message, string caption, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton) { if (_CurrentContext != null && MainActivity != null) { Action<bool> callback = OnConfirmCallBack; _IsCurrentlyInConfirmProcess = true; Action messageBoxDelegate = () => MessageBox.Show(((Activity)MainActivity), callback, message, caption, buttons); RunOnMainUiThread(messageBoxDelegate); while (_IsCurrentlyInConfirmProcess) { Thread.Sleep(1000); } } return _ConfirmBoxResult ? DialogResult.OK : DialogResult.No; } private void OnConfirmCallBack(bool confirmResult) { _ConfirmBoxResult = confirmResult; _IsCurrentlyInConfirmProcess = false; } private bool _ConfirmBoxResult = false; private bool _IsCurrentlyInConfirmProcess = false; 

Espero que esto pueda ayudar a alguien, los detalles completos de la solución se pueden encontrar aquí

FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.