Android-Alert Dialog
Dialogue is a little window that displays messages asking the user to choose or provide more information. Gives options like Ok and cancel.
Now write the code under the activity_main.xml, and this is the screen that is visible before opening the alert.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" 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:text="Hello here is a Alert Dialog." app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> |
Under the MainActivity.java create an alert that is created programmatically.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.example.alertdialog; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); 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 !"); builder.setCancelable(false); builder.setPositiveButton("Yes", (DialogInterface.OnClickListener) (dialog, which) -> { // When the user click yes button then app will close finish(); }); builder.setNegativeButton("No", (DialogInterface.OnClickListener) (dialog, which) -> { // If user click no then dialog box is canceled. dialog.cancel(); }); AlertDialog alertDialog = builder.create(); // Show the Alert Dialog box alertDialog.show(); } } |