How do I display an alert dialog on Android?

2018-12-31 06:21发布

I want to display a dialog/popup window with a message to the user that shows "Are you sure you want to delete this entry?" with one button that says 'Delete'. When Delete is touched, it should delete that entry, otherwise nothing.

I have written a click listener for those buttons, but how do I invoke a dialog or popup and its functionality?

26条回答
梦该遗忘
2楼-- · 2018-12-31 06:56

Just a simple one! Create a dialog method, something like this anywhere in your Java class:

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

Now create Layout XML dialog_demo.xml and create your UI/design. Here is a sample one I created for demo purposes:

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

Now you can call openDialog() from anywhere you like :) Here is the screenshot of above code.

Enter image description here

Note that text and color are used from strings.xml and colors.xml. You can define your own.

查看更多
刘海飞了
3楼-- · 2018-12-31 06:56

I'd like to add on David Hedlund great answer by sharing a more dynamic method than what he posted so it can be used when you do have a negative action to perform and when you don't, i hope it helps.

private void showAlertDialog(@NonNull Context context, @NonNull String alertDialogTitle, @NonNull String alertDialogMessage, @NonNull String positiveButtonText, @Nullable String negativeButtonText, @NonNull final int positiveAction, @Nullable final Integer negativeAction, @NonNull boolean hasNegativeAction)
{
    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(alertDialogTitle)
            .setMessage(alertDialogMessage)
            .setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (positiveAction)
                    {
                        case 1:
                            //TODO:Do your positive action here 
                            break;
                    }
                }
            });
            if(hasNegativeAction || negativeAction!=null || negativeButtonText!=null)
            {
            builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (negativeAction)
                    {
                        case 1:
                            //TODO:Do your negative action here
                            break;
                        //TODO: add cases when needed
                    }
                }
            });
            }
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.show();
}
查看更多
有味是清欢
4楼-- · 2018-12-31 06:56

You can create Activity and extends AppCompatActivity. Then in the Manifest put next style:

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

Inflate it by Buttons and TextViews

Then use this like a dialog.

For example, in the linearLayout I fill next parameters:

android:layout_width="300dp"
android:layout_height="wrap_content"
查看更多
大哥的爱人
5楼-- · 2018-12-31 06:59

for me

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();
查看更多
明月照影归
6楼-- · 2018-12-31 06:59

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

You will get the following output.

android alert dialog

To view alert dialog tutorial use the link below.

Android Alert Dialog Tutorial

查看更多
何处买醉
7楼-- · 2018-12-31 07:00

The code which David Hedlund has posted gave me the error:

Unable to add window — token null is not valid

If you are getting the same error use the below code. It works!!

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();
        }
    }
});
查看更多
登录 后发表回答