Как отобразить диалоговое окно с предупреждением на Android?

Я хочу отобразить диалоговое / всплывающее окно с сообщением для пользователя, которое показывает: «Вы уверены, что хотите удалить эту запись?» с помощью одной кнопки с надписью «Удалить». При касании Delete эта запись должна быть удалена, в противном случае ничего.

Я написал прослушиватель щелчков для этих кнопок, но как мне вызвать диалоговое окно или всплывающее окно и его функциональность?


person Community    schedule 22.01.2010    source источник
comment
Вот вы: developer.android.com/guide/topics/ui/dialogs. html   -  person Michaël Polla    schedule 25.07.2016
comment
Почему бы вам не использовать библиотеку диалогового окна материалов !?   -  person Vivek_Neel    schedule 28.07.2016
comment
Для примеров предупреждений с одной, двумя и тремя кнопками: см. этот ответ.   -  person Suragch    schedule 20.04.2017


Ответы (33)


Вы можете использовать для этого AlertDialog и построить его, используя его Builder класс. В приведенном ниже примере используется конструктор по умолчанию, который принимает только Context, поскольку диалоговое окно наследует правильную тему из контекста, который вы передаете, но есть также конструктор, который позволяет вам указать конкретный ресурс темы в качестве второго параметра, если вы хотите Сделай так.

new AlertDialog.Builder(context)
    .setTitle("Delete entry")
    .setMessage("Are you sure you want to delete this entry?")

    // Specifying a listener allows you to take an action before dismissing the dialog.
    // The dialog is automatically dismissed when a dialog button is clicked.
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // Continue with delete operation
        }
     })

    // A null listener allows the button to dismiss the dialog and take no further action.
    .setNegativeButton(android.R.string.no, null)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();
person Community    schedule 22.01.2010
comment
не следует ли AlertDialog.Builder(this) заменить на AlertDialog.Builder(className.this)? - person Apurva; 03.02.2015
comment
не обязательно. он нужен, если вы строите диалоговое окно с предупреждением из какого-либо слушателя. - person Alpha; 24.02.2015
comment
Имейте в виду, что AlertDialog.Builder нельзя закрыть с помощью метода dismiss (). Вы также можете использовать AlertDialog dialog = new AlertDialog.Builder (context) .create (); и вы сможете вызвать для него dismiss () в обычном режиме. - person Fustigador; 04.09.2015
comment
Не работал с выбором элементов ящика, но этот сработал: stackoverflow.com/a/26097588/1953178 - person Amr Hossam; 05.11.2015
comment
Неправда @Fustigador - person Ajay; 05.08.2016
comment
в моей деятельности я получаю данные api с продуктами в одном массиве и категориями в другом массиве, сначала нужно установить все продукты для повторного просмотра и щелкнуть параметры категорий, значок меню отобразит всплывающее окно / диалоговое окно с данными категорий, которые уже получены, если пользователь выберет категорию один раз, снова вернет выбранный элемент и вызовет api и обновите recycelerview на основе данных выбранной категории, пожалуйста, помогите мне - person Harsha; 24.08.2016
comment
@Fustigador в onClick(), DialogInterface dialog можно использовать как dialog.dismiss(), чтобы закрыть диалог. - person rupinderjeet; 28.09.2016
comment
@DavidBuilder: в этом примере используется DialogFragment или напрямую используется AlertDialog? Я думал, что прямое использование устарело. - person cpx; 17.01.2017
comment
@AmroShafie Разве код не делает это (диалоговое окно закрытия предупреждения) для меня? - person nitin; 27.02.2018
comment
Я продолжаю получать это исключение: android.view.WindowManager $ BadTokenException: Невозможно добавить окно - нулевой токен не предназначен для приложения в android.view.ViewRootImpl.setView (ViewRootImpl.java:567) при вызове .show () - person Sold Out; 26.08.2018
comment
К моему комментарию .. Мне нужно передать YourActivityName.this вместо getApplicationContext () в качестве параметра контекста .. - person Sold Out; 26.08.2018
comment
Лучше всего использовать Mainactivity.this с новым AlertDialog.Builder. - person SWIK; 08.06.2021

Попробуйте этот код:

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();
person Community    schedule 22.11.2012
comment
+1. Это гораздо лучший способ сделать это. @Mahesh создал экземпляр диалога, поэтому он доступен для cancel() и так далее. - person Subby; 03.08.2014
comment
где вы должны поместить это в свой код, чтобы точно создать конструктор? Я знаю, когда ты им пользуешься. - person Micro; 21.09.2015
comment
@MicroR В любом месте, где он будет запускаться, когда вы хотите получить предупреждение. Вы можете поместить его, например, в метод, на который указывает атрибут кнопки onClick. - person Caelum; 15.10.2015
comment
builder1.create() необходимо, потому что, кажется, он работает нормально, когда вы вызываете builder1.show() напрямую? - person razz; 04.01.2016
comment
@razzak да, это необходимо, потому что он предоставляет нам экземпляр диалога. мы можем использовать экземпляр диалога для доступа к конкретному методу диалога - person Mahesh; 05.01.2016
comment
Я пробую этот метод, но всплывающее окно с предупреждением сразу же исчезает, не давая мне времени прочитать его. У меня явно нет времени нажимать на кнопки, чтобы закрыть его. Есть идеи, почему? - person lweingart; 06.01.2016
comment
Неважно, я нашел причину, по которой я запускал новое намерение, и он не ждал, пока откроются мои окна предупреждений, как я мог найти здесь: stackoverflow.com/questions/6336930/ - person lweingart; 06.01.2016
comment
Этот код отлично работает. Однако я хочу поместить все свои предупреждения в отдельный класс Java. Метод будет статическим, поэтому я могу вызвать Alerts.error1(). Однако я не уверен, как передать context, поскольку this не работает, когда он находится в другом классе. Я пробовал Alerts.error1(view), но это бросило мне Error:(13, 63) error: non-static variable this cannot be referenced from a static context. - person Regis; 08.11.2017
comment
@Regis вам нужно передать контекст в качестве параметра для ошибки метода, например Alert.error (context); - person Mahesh; 17.11.2017

Код, который опубликовал Дэвид Хедлунд, дал мне ошибку:

Невозможно добавить окно - нулевой токен недействителен

Если вы получаете ту же ошибку, используйте приведенный ниже код. Оно работает!!

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();
        }
    }
});
person Community    schedule 16.06.2014
comment
Нам не нужно использовать одновременно create() и show(), поскольку show() уже создает диалог с описанным содержимым. Согласно документации, create() Создает AlertDialog с аргументами, предоставленными этому построителю. Это не Dialog.show () диалог. Это позволяет пользователю выполнять дополнительную обработку перед отображением диалогового окна. Используйте show (), если у вас нет других действий по обработке и вы хотите, чтобы это было создано и отображено. Поэтому полезно использовать create(), только если вы планируете показывать позже, и вы загружаете его содержимое заранее. - person Ruchir Baronia; 06.08.2016
comment
Поменял параметр с getApplicationContext() на MyActivity.this и начал работать. - person O-9; 25.06.2019

Используйте 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();

Вы получите следующий результат.

диалоговое окно предупреждения Android

Чтобы просмотреть руководство по диалоговому окну предупреждений, используйте ссылку ниже.

Руководство по диалоговому окну предупреждений Android

person Community    schedule 12.05.2018

Просто простой! Создайте метод диалога, примерно так, в любом месте вашего класса 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();
}

Теперь создайте Layout XML dialog_demo.xml и создайте свой UI / дизайн. Вот образец, который я создал для демонстрационных целей:

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

Теперь вы можете позвонить openDialog() из любого места :) Вот скриншот приведенного выше кода.

Введите описание изображения здесь

Обратите внимание, что текст и цвет используются от strings.xml и colors.xml. Вы можете определить свое собственное.

person Community    schedule 22.05.2015
comment
Класс Dialog является базовым классом для диалогов, но вам следует избегать создания экземпляров Dialog напрямую. Вместо этого используйте один из следующих подклассов: AlertDialog, DatePickerDialog or TimePickerDialog (из developer.android.com/ руководство / themes / ui / dialogs.html) - person sweisgerber.dev; 10.03.2016
comment
Здесь нельзя нажать кнопку «Отменить» и «Принять». - person c1ph4; 17.02.2018

В настоящее время лучше использовать DialogFragment вместо прямого создания AlertDialog.

person Community    schedule 30.05.2014
comment
Кроме того, у меня было так много проблем, пытаясь избавиться от странного системного фона AlertDialog, когда он раздувал его с помощью моего пользовательского представления содержимого. - person goRGon; 24.07.2015

Вы можете использовать этот код:

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();
person Community    schedule 09.04.2013
comment
dialog.cancel (); не должен вызываться вторым слушателем - person demaksee; 30.08.2013
comment
ссылка на этот учебник не работает. Вы перейдете на store.hp.com/ - person JamesDeHart; 26.07.2015

для меня

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();
person Community    schedule 24.05.2017

Это базовый пример создания диалогового окна предупреждения:

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

введите описание изображения здесь

person Community    schedule 27.01.2017

Это определенно поможет вам. Попробуйте этот код: при нажатии кнопки вы можете поместить одну, две или три кнопки с диалоговым окном предупреждения ...

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();
    }
});
person Community    schedule 25.07.2013

showDialog(MainActivity.this, "title", "message", "OK", "Cancel", {...}, {...});

Котлин

fun showDialog(context: Context, title: String, msg: String,
               positiveBtnText: String, negativeBtnText: String?,
               positiveBtnClickListener: DialogInterface.OnClickListener,
               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
}

Джава

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;
}
person Community    schedule 01.10.2018

Я создал диалог для того, чтобы спросить человека, хочет ли он позвонить человеку или нет.

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();
    }
}
person Community    schedule 22.04.2014

вы можете попробовать это ....

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

Для получения дополнительной информации проверьте эту ссылку ...

person Community    schedule 15.04.2017

Попробуйте этот код

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();
person Community    schedule 07.02.2018

Вы можете создать диалоговое окно, используя AlertDialog.Builder

Попробуйте это:

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

Чтобы изменить цвет положительных и отрицательных кнопок диалогового окна Alert, вы можете написать две строки ниже после alertDialog.show();

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

введите описание изображения здесь

person Community    schedule 06.04.2018

Просто будьте осторожны, когда хотите закрыть диалоговое окно - используйте dialog.dismiss(). В своей первой попытке я использовал dismissDialog(0) (который я, вероятно, скопировал откуда-то), который иногда работает. Использование объекта, поставляемого системой, кажется более безопасным выбором.

person Community    schedule 18.06.2010

Я хотел бы добавить отличный ответ Дэвида Хедлунда, поделившись более динамичным методом, чем то, что он опубликовал, чтобы его можно было использовать, когда у вас есть негативное действие, которое нужно выполнить, а когда у вас нет, я надеюсь, это поможет.

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();
}
person Community    schedule 11.10.2018

Я использовал этот метод AlertDialog в кнопке onClick:

button.setOnClickListener(v -> {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);
    View view = layoutInflaterAndroid.inflate(R.layout.cancel_dialog, null);
    builder.setView(view);
    builder.setCancelable(false);
    final AlertDialog alertDialog = builder.create();
    alertDialog.show();

    view.findViewById(R.id.yesButton).setOnClickListener(v -> onBackPressed());
    view.findViewById(R.id.nobutton).setOnClickListener(v -> alertDialog.dismiss());
});

dialog.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<TextView
    android:id="@+id/textmain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:gravity="center"
    android:padding="5dp"
    android:text="@string/warning"
    android:textColor="@android:color/black"
    android:textSize="18sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


<TextView
    android:id="@+id/textpart2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:gravity="center"
    android:lines="2"
    android:maxLines="2"
    android:padding="5dp"
    android:singleLine="false"
    android:text="@string/dialog_cancel"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textmain" />


<TextView
    android:id="@+id/yesButton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="40dp"
    android:layout_marginBottom="5dp"
    android:background="#87cefa"
    android:gravity="center"
    android:padding="10dp"
    android:text="@string/yes"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textpart2" />


<TextView
    android:id="@+id/nobutton"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="40dp"
    android:layout_marginTop="5dp"
    android:layout_marginEnd="40dp"
    android:background="#87cefa"
    android:gravity="center"
    android:padding="10dp"
    android:text="@string/no"
    android:textAlignment="center"
    android:textColor="@android:color/black"
    android:textSize="15sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/yesButton" />


<TextView
    android:layout_width="match_parent"
    android:layout_height="20dp"
    android:layout_margin="5dp"
    android:padding="10dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/nobutton" />
</androidx.constraintlayout.widget.ConstraintLayout>
person Community    schedule 19.03.2019
comment
Обновите предоставленный код, объяснив, что именно он делает. - person wscourge; 19.03.2019

В библиотеке компонентов материала вы можете просто использовать MaterialAlertDialogBuilder

   MaterialAlertDialogBuilder(context)
        .setMessage("Are you sure you want to delete this entry?")
        .setPositiveButton("Delete") { dialog, which ->
            // Respond to positive button press
        }
        .setNegativeButton("Cancel") { dialog, which ->
            // Respond to positive button press
        }   
        .show()

введите описание изображения здесь

С помощью Compose 1.0.0-beta03 вы можете использовать:

val openDialog = remember { mutableStateOf(true) }

if (openDialog.value) {
    AlertDialog(
        onDismissRequest = {
            // Dismiss the dialog when the user clicks outside the dialog or on the back
            // button. If you want to disable that functionality, simply use an empty
            // onCloseRequest.
            openDialog.value = false
        },
        title = null,
        text = {
            Text(
                "Are you sure you want to delete this entry?"
            )
        },
        confirmButton = {
            TextButton(
                onClick = {
                    openDialog.value = false
                }
            ) {
                Text("Delete")
            }
        },
        dismissButton = {
            TextButton(
                onClick = {
                    openDialog.value = false
                }
            ) {
                Text("Cancel")
            }
        }
    )
}

введите описание изображения здесь

person Community    schedule 03.04.2021

вы также можете попробовать этот способ, он предоставит вам диалоги стиля материала

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();
}
person Community    schedule 19.12.2015

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

Также посетите мой блог о диалогах в Android, вы найдете все подробности здесь: http://www.fahmapps.com/2016/09/26/dialogs-in-android-part1/.

person Community    schedule 26.09.2016

Сделайте этот статический метод и используйте его где угодно.

public static void showAlertDialog(Context context, String title, String message, String posBtnMsg, String negBtnMsg) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.setPositiveButton(posBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.setNegativeButton(negBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

        }
person Community    schedule 21.01.2019

Самое простое решение для разработчиков Котлина

val alertDialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
    alertDialogBuilder.setMessage(msg)
    alertDialogBuilder.setCancelable(true)

    alertDialogBuilder.setPositiveButton(
        getString(android.R.string.ok)
    ) { dialog, _ ->
        dialog.cancel()
    }

    val alertDialog: AlertDialog = alertDialogBuilder.create()
    alertDialog.show()
person Community    schedule 28.09.2020

Диалог предупреждения с текстом редактирования

AlertDialog.Builder builder = new AlertDialog.Builder(context);//Context is activity context
final EditText input = new EditText(context);
builder.setTitle(getString(R.string.remove_item_dialog_title));
        builder.setMessage(getString(R.string.dialog_message_remove_item));
 builder.setTitle(getString(R.string.update_qty));
            builder.setMessage("");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setHint(getString(R.string.enter_qty));
            input.setTextColor(ContextCompat.getColor(context, R.color.textColor));
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            input.setText("String in edit text you want");
            builder.setView(input);
   builder.setPositiveButton(getString(android.R.string.ok),
                (dialog, which) -> {

//Positive button click event
  });

 builder.setNegativeButton(getString(android.R.string.cancel),
                (dialog, which) -> {
//Negative button click event
                });
        AlertDialog dialog = builder.create();
        dialog.show();
person Community    schedule 21.01.2019

Это делается в котлине

val builder: AlertDialog.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
        } else {
            AlertDialog.Builder(this)
        }
        builder.setTitle("Delete Alert!")
                .setMessage("Are you want to delete this entry?")
                .setPositiveButton("YES") { dialog, which ->

                }
                .setNegativeButton("NO") { dialog, which ->

                }
                .setIcon(R.drawable.ic_launcher_foreground)
                .show()
person Community    schedule 07.01.2019

AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("This is Title");
    builder.setMessage("This is message for Alert Dialog");
    builder.setPositiveButton("Positive Button", (dialog, which) -> onBackPressed());
    builder.setNegativeButton("Negative Button", (dialog, which) -> dialog.cancel());
    builder.show();

Это аналогичный способ создания диалогового окна с предупреждением с помощью некоторой строчки кода.

person Community    schedule 26.11.2018

Код для удаления записи из списка

 /*--dialog for delete entry--*/
private void cancelBookingAlert() {
    AlertDialog dialog;
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogCustom);
    alertDialog.setTitle("Delete Entry");
    alertDialog.setMessage("Are you sure you want to delete this entry?");
    alertDialog.setCancelable(false);

    alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
           //code to delete entry
        }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    dialog = alertDialog.create();
    dialog.show();
}

Вызов метода выше при нажатии кнопки удаления

person Community    schedule 26.12.2018

С помощью Anko (официальная библиотека от разработчиков Kotlin), вы можете просто использовать

alert("Alert title").show()

или более сложный:

alert("Hi, I'm Roy", "Have you tried turning it off and on again?") {
    yesButton { toast("Oh…") }
    noButton {}
}.show()

Чтобы импортировать Anko:

implementation "org.jetbrains.anko:anko:0.10.8"
person Community    schedule 19.04.2019

Вы можете создать Activity и расширить AppCompatActivity. Затем в манифесте поместите следующий стиль:

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

Раздуть его кнопками и TextViews

Затем используйте это как диалог.

Например, в linearLayout я заполняю следующие параметры:

android:layout_width="300dp"
android:layout_height="wrap_content"
person Community    schedule 06.07.2018

В последние несколько дней мои коллеги продолжают спрашивать меня об использовании AlertDialog в Xamarin.Android, и почти все они отправили этот вопрос в качестве ссылки, которую они прочитали, прежде чем спросить меня (и не нашли ответа), так что вот Xamarin.Android (C#) версия:

var alertDialog = new AlertDialog.Builder(this) // this: Activity
    .SetTitle("Hello!")
    .SetMessage("Are you sure?")
    .SetPositiveButton("Ok", (sender, e) => { /* ok things */ })
    .SetNegativeButton("Cancel", (sender, e) => { /* cancel things */ })
    .Create();

alertDialog.Show();

// you can customize your AlertDialog, like so
var tvMessage = alertDialog.FindViewById<TextView>(Android.Resource.Id.Message);
tvMessage.TextSize = 13;
// ...
person Community    schedule 20.04.2019

Kotlin Custom dialog: Если вы хотите создать настраиваемый диалог

Dialog(activity!!, R.style.LoadingIndicatorDialogStyle)
        .apply {
            // requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCancelable(true)
            setContentView(R.layout.define_your_custom_view_id_here)

            //access your custom view buttons/editText like below.z
            val createBt = findViewById<TextView>(R.id.clipboard_create_project)
            val cancelBt = findViewById<TextView>(R.id.clipboard_cancel_project)
            val clipboard_et = findViewById<TextView>(R.id.clipboard_et)
            val manualOption =
                findViewById<TextView>(R.id.clipboard_manual_add_project_option)

            //if you want to perform any operation on the button do like this

            createBt.setOnClickListener {
                //handle your button click here
                val enteredData = clipboard_et.text.toString()
                if (enteredData.isEmpty()) {
                    Utils.toast("Enter project details")
                } else {
                    navigateToAddProject(enteredData, true)
                    dismiss()
                }
            }

            cancelBt.setOnClickListener {
                dismiss()
            }
            manualOption.setOnClickListener {
                navigateToAddProject("", false)
                dismiss()
            }
            show()
        }

Создайте стиль LoadingIndicatorDialogStyle в style.xml

<style name="LoadingIndicatorDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:statusBarColor">@color/black_transperant</item>
<item name="android:layout_gravity">center</item>
<item name="android:background">@android:color/transparent</item>
<!--<item name="android:windowAnimationStyle">@style/MaterialDialogSheetAnimation</item>-->
person Community    schedule 23.11.2020

person    schedule
comment
Код Yout неверен, вам нужно изменить setPositiveButton (отменить на setNegativeButton (отменить - person Benoist Laforge; 21.01.2015
comment
Спасибо, это произошло по ошибке ... На самом деле я хочу проверить, может ли кто-нибудь глубоко проверить опубликованный код или нет. И ты единственный ... еще раз спасибо .. - person Anil Singhania; 23.01.2015

person    schedule
comment
Объяснение пожалуйста - person GYaN; 26.03.2018
comment
Никаких объяснений, пожалуйста. Этот ответ идеален, и любая попытка добавить слова, чтобы утихомирить Пояснение, пожалуйста, боты только усугубит ситуацию. - person Don Hatch; 12.04.2018