¿Cómo se muestra un cuadro de diálogo de alerta en Android?

Quiero mostrar una ventana de diálogo / ventana emergente con un mensaje para el usuario que muestra “¿Seguro que quieres eliminar esta entrada?” con un botón que dice ‘Eliminar’. Cuando se toca Delete , debe eliminar esa entrada, de lo contrario, nada.

He escrito un oyente de clic para esos botones, pero ¿cómo invoco un diálogo o una ventana emergente y su funcionalidad?

    Puede usar el generador de alertas para esto:

      AlertDialog.Builder builder; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert); } else { builder = new AlertDialog.Builder(context); } builder.setTitle("Delete entry") .setMessage("Are you sure you want to delete this entry?") .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // continue with delete } }) .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // do nothing } }) .setIcon(android.R.drawable.ic_dialog_alert) .show(); 

    Prueba este código:

     AlertDialog.Builder builder1 = new AlertDialog.Builder(context); builder1.setMessage("Write your message here."); builder1.setCancelable(true); builder1.setPositiveButton( "Yes", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); builder1.setNegativeButton( "No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert11 = builder1.create(); alert11.show(); 

    El código que David Hedlund publicó me dio el error:

    No se puede agregar la ventana – token null no es válido

    Si obtiene el mismo error, use el siguiente código. ¡¡Funciona!!

     runOnUiThread(new Runnable() { @Override public void run() { if (!isFinishing()){ new AlertDialog.Builder(YourActivity.this) .setTitle("Your Alert") .setMessage("Your Message") .setCancelable(false) .setPositiveButton("ok", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // Whatever... } }).show(); } } }); 

    ¡Simplemente uno simple! Cree un método de diálogo, algo así en cualquier lugar de su clase Java:

     public void openDialog() { final Dialog dialog = new Dialog(context); // Context, this, etc. dialog.setContentView(R.layout.dialog_demo); dialog.setTitle(R.string.dialog_title); dialog.show(); } 

    Ahora crea Layout XML dialog_demo.xml y crea tu UI / diseño. Aquí hay una muestra que creé para demostraciones:

     < ?xml version="1.0" encoding="utf-8"?>        

    Ahora puede llamar a openDialog() desde cualquier lugar que desee 🙂 Aquí está la captura de pantalla del código anterior.

    Ingrese la descripción de la imagen aquí

    Tenga en cuenta que el texto y el color se utilizan desde strings.xml y colors.xml . Puedes definir el tuyo

    Hoy en día es mejor usar DialogFragment en lugar de la creación directa de AlertDialog.

    Puedes usar este código:

     AlertDialog.Builder alertDialog2 = new AlertDialog.Builder( AlertDialogActivity.this); // Setting Dialog Title alertDialog2.setTitle("Confirm Delete..."); // Setting Dialog Message alertDialog2.setMessage("Are you sure you want delete this file?"); // Setting Icon to Dialog alertDialog2.setIcon(R.drawable.delete); // Setting Positive "Yes" Btn alertDialog2.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT) .show(); } }); // Setting Negative "NO" Btn alertDialog2.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT) .show(); dialog.cancel(); } }); // Showing Alert Dialog alertDialog2.show(); 

    para mi

     new AlertDialog.Builder(this) .setTitle("Closing application") .setMessage("Are you sure you want to exit?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).setNegativeButton("No", null).show(); 
     // Dialog box public void dialogBox() { AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this); alertDialogBuilder.setMessage("Click on Image for tag"); alertDialogBuilder.setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); alertDialogBuilder.setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { } }); AlertDialog alertDialog = alertDialogBuilder.create(); alertDialog.show(); } 

    Esta es una muestra básica de cómo crear un diálogo de alerta :

     AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this); dialog.setCancelable(false); dialog.setTitle("Dialog on Android"); dialog.setMessage("Are you sure you want to delete this entry?" ); dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { //Action for "Delete". } }) .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Action for "Cancel". } }); final AlertDialog alert = dialog.create(); alert.show(); 

    enter image description here

    Utilice AlertDialog.Builder

      AlertDialog alertDialog = new AlertDialog.Builder(this) //set icon .setIcon(android.R.drawable.ic_dialog_alert) //set title .setTitle("Are you sure to Exit") //set message .setMessage("Exiting will call finish() method") //set positive button .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //set what would happen when positive button is clicked finish(); } }) //set negative button .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //set what should happen when negative button is clicked Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show(); } }) .show(); 

    Obtendrá la siguiente salida.

    diálogo de alerta de Android

    Para ver el tutorial de diálogo de alerta, use el siguiente enlace.

    Tutorial de diálogo de alerta de Android

    Esto es definitivamente ayuda para ti. Pruebe este código: al hacer clic en un botón, puede poner uno, dos o tres botones con un diálogo de alerta …

     SingleButtton.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // Creating alert Dialog with one Button AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create(); // Setting Dialog Title alertDialog.setTitle("Alert Dialog"); // Setting Dialog Message alertDialog.setMessage("Welcome to Android Application"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.tick); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { // Write your code here to execute after dialog closed Toast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show(); } }); // Showing Alert Message alertDialog.show(); } }); btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // Creating alert Dialog with two Buttons AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this); // Setting Dialog Title alertDialog.setTitle("Confirm Delete..."); // Setting Dialog Message alertDialog.setMessage("Are you sure you want delete this?"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.delete); // Setting Positive "Yes" Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { // Write your code here to execute after dialog Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show(); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to execute after dialog Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show(); dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } }); btnAlertThreeBtns.setOnClickListener(new View.OnClickListener() { public void onClick(View arg0) { // Creating alert Dialog with three Buttons AlertDialog.Builder alertDialog = new AlertDialog.Builder( AlertDialogActivity.this); // Setting Dialog Title alertDialog.setTitle("Save File..."); // Setting Dialog Message alertDialog.setMessage("Do you want to save this file?"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.save); // Setting Positive Yes Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // User pressed Cancel button. Write Logic Here Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show(); } }); // Setting Negative No Button... Neutral means in between yes and cancel button alertDialog.setNeutralButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // User pressed No button. Write Logic Here Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT) .show(); } }); // Setting Positive "Cancel" Button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // User pressed Cancel button. Write Logic Here Toast.makeText(getApplicationContext(), "You clicked on Cancel", Toast.LENGTH_SHORT).show(); } }); // Showing Alert Message alertDialog.show(); } }); 

    He creado un diálogo para preguntarle a una persona si quiere llamar a una persona o no.

     import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.Toast; public class Firstclass extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.first); ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig); imageViewCall.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { try { showDialog("0728570527"); } catch (Exception e) { e.printStackTrace(); } } }); } public void showDialog(final String phone) throws Exception { AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this); builder.setMessage("Ring: " + phone); builder.setPositiveButton("Ring", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL); callIntent.setData(Uri.parse("tel:" + phone)); startActivity(callIntent); dialog.dismiss(); } }); builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } } 

    puedes probar esto …

      AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this); dialog.setCancelable(false); dialog.setTitle("Dialog on Android"); dialog.setMessage("Are you sure you want to delete this entry?" ); dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { //Action for "Delete". } }) .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Action for "Cancel". } }); final AlertDialog alert = dialog.create(); alert.show(); 

    Para obtener más información, consulte este enlace …

    Solo tenga cuidado cuando desee cerrar el diálogo: use dialog.dismiss() . En mi primer bash usé dismissDialog(0) (que probablemente copié de algún lugar) que a veces funciona. Usar el objeto que el sistema suministra suena como una opción más segura.

     Try this code AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( MainActivity.this); // set title alertDialogBuilder.setTitle("AlertDialog Title"); // set dialog message alertDialogBuilder .setMessage("Some Alert Dialog message.") .setCancelable(false) .setPositiveButton("OK",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { Toast.makeText(this, "OK button click ", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("CANCEL",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Toast.makeText(this, "CANCEL button click ", Toast.LENGTH_SHORT).show(); dialog.cancel(); } }); // create alert dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); 
      new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show(); 

    Puede crear el cuadro de diálogo usando AlertDialog.Builder

    Prueba esto:

     AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage("Are you sure you want to delete this entry?"); builder.setPositiveButton("Yes, please", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //perform any action Toast.makeText(getApplicationContext(), "Yes clicked", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //perform any action Toast.makeText(getApplicationContext(), "No clicked", Toast.LENGTH_SHORT).show(); } }); //creating alert dialog AlertDialog alertDialog = builder.create(); alertDialog.show(); 

    Para cambiar el color de los botones positivos y negativos del cuadro de diálogo Alerta, puede escribir las dos líneas siguientes después de alertDialog.show();

     alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary)); alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark)); 

    enter image description here

    puedes intentarlo de esta manera también, te proporcionará diálogos de estilo material

     private void showDialog() { String text2 = "Medi Notification";//for custom title color AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle(Html.fromHtml(text2)); String text3 = "You can complete your profile now or start using the app and come back later";//for custom message builder.setMessage(Html.fromHtml(text3)); builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { toast = Toast.makeText(getApplicationContext(), "DELETE", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { toast = Toast.makeText(getApplicationContext(), "CANCEL", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } }); builder.show(); } 
     public void showSimpleDialog(View view) { // Use the Builder class for convenient dialog construction AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setCancelable(false); builder.setTitle("AlertDialog Title"); builder.setMessage("Simple Dialog Message"); builder.setPositiveButton("OK!!!", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { // } }) .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); // Create the AlertDialog object and return it builder.create().show(); } 

    También consulte mi blog en Diálogos en Android, encontrará todos los detalles aquí: http://www.fahmapps.com/2016/09/26/dialogs-in-android-part1/ .

      new AlertDialog.Builder(context) .setTitle("title") .setMessage("message") .setPositiveButton(android.R.string.ok, null) .show(); 
     import android.app.*; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.widget.*; public class ShowPopUp extends Activity { PopupWindow popUp; LinearLayout layout; TextView tv; LayoutParams params; LinearLayout mainLayout; Button but; boolean click = true; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); popUp = new PopupWindow(this); layout = new LinearLayout(this); mainLayout = new LinearLayout(this); tv = new TextView(this); but = new Button(this); but.setText("Click Me"); but.setOnClickListener(new OnClickListener() { public void onClick(View v) { if (click) { popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10); popUp.update(50, 50, 300, 80); click = false; } else { popUp.dismiss(); click = true; } } }); params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layout.setOrientation(LinearLayout.VERTICAL); tv.setText("Hi this is a sample text for popup window"); layout.addView(tv, params); popUp.setContentView(layout); // popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10); mainLayout.addView(but, params); setContentView(mainLayout); } } 

    Puede crear Actividad y extiende AppCompatActivity. Luego, en el Manifest put next style:

       

    Inflarlo por botones y TextViews

    Luego usa esto como un diálogo.

    Por ejemplo, en lineLayout llene los siguientes parámetros:

     android:layout_width="300dp" android:layout_height="wrap_content"