Как создать диалоговое окно предупреждения в Android?
Диалоговое окно предупреждений показывает сообщение предупреждения и дает ответ в форме «да» или «нет». Диалоговое окно предупреждений отображает сообщение, чтобы предупредить вас, а затем в соответствии с вашим ответом обрабатывается следующий шаг. Диалоговое окно Android Alert построено с использованием трех полей: заголовка, области сообщения и кнопки действия.
Код диалогового окна предупреждения имеет три метода :
- Метод setTitle() для отображения заголовка диалогового окна предупреждения.
- Метод setMessage() для отображения сообщения
- Метод setIcon() используется для установки значка в диалоговом окне предупреждения.
Затем мы добавляем две кнопки, setPositiveButton и setNegativeButton в диалоговое окно оповещения, как показано ниже.
Пример:

Пошаговая реализация
Шаг 1. Создайте новый проект в Android Studio.
Чтобы создать новый проект в Android Studio, обратитесь к разделу «Как создать/запустить новый проект в Android Studio». Код для этого был предоставлен как на Java, так и на языке программирования Kotlin для Android.
Шаг 2: Работа с файлами XML
Далее перейдите к файлу activity_main.xml , представляющему UI проекта. Ниже приведен код файла activity_main.xml . Комментарии добавляются внутри кода, чтобы понять код более подробно.
XML
<?xml version="1.0" encoding="utf-8"?> android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="180dp" android:gravity="center_horizontal" android:text="Press The Back Button of Your Phone." android:textSize="30dp" android:textStyle="bold" /></RelativeLayout> |
Шаг 3: Работа с файлом MainActivity
Перейдите в файл MainActivity и обратитесь к следующему коду. Ниже приведен код файла MainActivity. Комментарии добавляются внутри кода, чтобы понять код более подробно.
Java
import android.content.DialogInterface;import android.os.Bundle;import androidx.appcompat.app.AlertDialog;import androidx.appcompat.app.AppCompatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Declare the onBackPressed method when the back button is pressed this method will call @Override public void onBackPressed() { // Create the object of AlertDialog Builder class AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // Set the message show for the Alert time builder.setMessage("Do you want to exit ?"); // Set Alert Title builder.setTitle("Alert !"); // Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show builder.setCancelable(false); // Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface. builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> { // When the user click yes button then app will close finish(); }); // Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface. builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> { // If user click no then dialog box is canceled. dialog.cancel(); }); // Create the Alert dialog AlertDialog alertDialog = builder.create(); // Show the Alert Dialog box alertDialog.show(); }} |
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AlertDialogimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } // Declare the onBackPressed method when the back button is pressed this method will call override fun onBackPressed() { // Create the object of AlertDialog Builder class val builder = AlertDialog.Builder(this) // Set the message show for the Alert time builder.setMessage("Do you want to exit ?") // Set Alert Title builder.setTitle("Alert !") // Set Cancelable false for when the user clicks on the outside the Dialog Box then it will remain show builder.setCancelable(false) // Set the positive button with yes name Lambda OnClickListener method is use of DialogInterface interface. builder.setPositiveButton("Yes") { // When the user click yes button then app will close dialog, which -> finish() } // Set the Negative button with No name Lambda OnClickListener method is use of DialogInterface interface. builder.setNegativeButton("No") { // If user click no then dialog box is canceled. dialog, which -> dialog.cancel() } // Create the Alert dialog val alertDialog = builder.create() // Show the Alert Dialog box alertDialog.show() }} |
Выход:
