Comment afficher un dialogue d'alerte sur Android?

je veux afficher une fenêtre de dialogue / popup avec un message à l'utilisateur qui montre "Êtes-vous sûr que vous voulez supprimer cette entrée?"avec un bouton 'Supprimer'. Lorsque Delete est touché, il devrait supprimer cette entrée, sinon rien.

j'ai écrit un écouteur de clic pour ces boutons, mais comment puis-je invoquer un dialogue ou popup et sa fonctionnalité?

864
demandé sur UMAR-MOBITSOLUTIONS 2010-01-22 10:37:11

23 réponses

vous pouvez utiliser le constructeur d'alerte pour ceci:

    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();
1582
répondu David Hedlund 2017-05-18 10:37:51

essayez ce code:

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();
302
répondu Mahesh 2015-12-19 10:55:43

le code que David Hedlund a posté m'a donné l'erreur:

impossible d'ajouter window - token null n'est pas valide

si vous obtenez la même erreur, utilisez le code ci-dessous. Il fonctionne!!

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();
        }
    }
});
79
répondu user3716835 2016-11-28 07:45:42

un simple! Créez une méthode de dialogue, quelque chose comme ceci n'importe où dans votre classe 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();
}

créez maintenant le format XML dialog_demo.xml et créez votre interface utilisateur/design. Voici un exemple que j'ai créé à des fins de démonstration:

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

    <TextView
        android:id="@+id/dialog_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/dialog_text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/dialog_info">

        <Button
            android:id="@+id/dialog_cancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:background="@color/dialog_cancel_bgcolor"
            android:text="Cancel"/>

        <Button
            android:id="@+id/dialog_ok"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:background="@color/dialog_ok_bgcolor"
            android:text="Agree"/>
    </LinearLayout>
</RelativeLayout>

Maintenant vous pouvez appeler openDialog() de n'importe où vous voulez :) Voici la capture d'écran du code ci-dessus.

Enter image description here

noter que le texte et la couleur sont utilisées de strings.xml et colors.xml . Vous pouvez définir la vôtre.

58
répondu Madan Sapkota 2015-12-19 11:25:44

de nos jours, il est préférable d'utiliser DialogFragment au lieu de la création directe AlertDialog.

46
répondu goRGon 2017-05-23 10:31:36

vous pouvez utiliser ce code:

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();
37
répondu romain guy 2016-07-09 03:18:53

pour moi

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();
31
répondu Hoàng Đăng 2017-05-24 15:11:43
// 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();
}
28
répondu Anil Singhania 2015-12-19 11:24:15

Utiliser AlertDialog.Constructeur

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

vous obtiendrez la sortie suivante.

android alert dialog

pour voir le tutoriel de dialogue Alerte utiliser le lien ci-dessous.

Tutoriel De Dialogue Alerte Android

17
répondu Richard Kamere 2018-05-12 17:54:49

ceci est un exemple de base de comment créer un dialogue D'alerte :

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

16
répondu Jorgesys 2017-01-27 17:12:16

C'est certainement de l'aide pour vous. Essayez ce code: en cliquant sur un bouton, vous pouvez mettre un, deux ou trois boutons avec un dialogue Alerte...

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();
    }
});
10
répondu Mitul Goti 2015-12-19 11:01:10

j'ai créé un dialogue pour demander à une personne si elle veut appeler une personne ou non.

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();
    }
}
10
répondu Nepster 2015-12-19 11:02:20

vous pouvez essayer cette....

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

pour plus d'informations,consultez ce lien...

9
répondu Tamzid Babu 2017-04-15 19:50:39
  new AlertDialog.Builder(context)
                                .setTitle("title")
                                .setMessage("message")
                                .setPositiveButton(android.R.string.ok, null)
                                .show();
6
répondu user3219477 2018-04-19 05:17:31

il suffit d'être prudent lorsque vous voulez rejeter le dialogue - utiliser dialog.dismiss() . Dans ma première tentative, j'ai utilisé dismissDialog(0) (que j'ai probablement copié d'un endroit) qui parfois œuvres. L'utilisation de l'objet fourni par le système semble être un choix plus sûr.

4
répondu Ivaylo Novakov 2017-02-23 12:06:18

vous pouvez créer la boîte de dialogue en utilisant AlertDialog.Builder

essayez ceci:

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

pour changer la couleur des boutons positifs et négatifs de la boîte de dialogue Alerte, vous pouvez écrire les deux lignes suivantes après 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

4
répondu Hassnain Jamil 2018-04-06 10:43:16
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();
3
répondu Faxriddin Abdullayev 2018-02-07 11:24:40
   new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show();
3
répondu Adeeb karim 2018-03-26 06:22:51

vous pouvez essayer de cette façon aussi, il vous fournira des dialogues de style matériel

private void showDialog()
{
    String text2 = "<font color=#212121>Medi Notification</font>";//for custom title color

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "<font color=#A4A4A4>You can complete your profile now or start using the app and come back later</font>";//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();
}
2
répondu Nilabja 2015-12-19 11:02:25
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();
}

également consulter mon blog sur Dialogs en Android, vous trouverez tous les détails ici: http://www.fahmapps.com/2016/09/26/dialogs-in-android-part1 / .

2
répondu Faheem 2016-09-26 15:09:24
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);
       }
   }
1
répondu Amit Desale 2016-08-08 07:01:10

vous pouvez créer L'activité et étend L'Appcompatactivité. Puis dans le Manifeste mettre le style suivant:

<activity android:name=".YourCustomDialog"
            android:theme="Theme.AppCompat.Light.Dialog">
</activity>

le gonfler par des boutons et des TextViews

alors utilisez ceci comme un dialogue.

par exemple, dans la linéarité, je remplis les paramètres suivants:

android:layout_width="300dp"
android:layout_height="wrap_content"
0
répondu EvgeTymo 2018-07-06 07:40:19

In Kotlin

fun showDialog(@NonNull context: Context, @NonNull title: String, @NonNull msg: String,
               @NonNull positiveBtnText: String, @Nullable negativeBtnText: String?,
               @NonNull positiveBtnClickListener: DialogInterface.OnClickListener,
               @Nullable negativeBtnClickListener: DialogInterface.OnClickListener): AlertDialog {
    val builder = AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(msg)
            .setCancelable(true)
            .setPositiveButton(positiveBtnText, positiveBtnClickListener)
    if (negativeBtnText != null)
        builder.setNegativeButton(negativeBtnText, negativeBtnClickListener)
    val alert = builder.create()
    alert.show()
    return alert
}

En Java

public static AlertDialog showDialog(@NonNull Context context, @NonNull String title, @NonNull String msg,
                                     @NonNull String positiveBtnText, @Nullable String negativeBtnText,
                                     @NonNull DialogInterface.OnClickListener positiveBtnClickListener,
                                     @Nullable DialogInterface.OnClickListener negativeBtnClickListener) {
    AlertDialog.Builder builder = new AlertDialog.Builder(context)
            .setTitle(title)
            .setMessage(msg)
            .setCancelable(true)
            .setPositiveButton(positiveBtnText, positiveBtnClickListener);
    if (negativeBtnText != null)
        builder.setNegativeButton(negativeBtnText, negativeBtnClickListener);
    AlertDialog alert = builder.create();
    alert.show();
    return alert;
}
0
répondu Khemraj 2018-10-01 10:53:24