Create an application that will Demonstrate Dialog Box Control In Android

activity_main.xml

<?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="match_parent">

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:layout_centerInParent="true"
android:text="Close app" />


</RelativeLayout>

MainActivity.java

package com.example.helloworld;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
public static Button closeButton;
AlertDialog.Builder builder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

closeButton = (Button) findViewById(R.id.button);
builder = new AlertDialog.Builder(this);
closeButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

//Uncomment the below code to Set the message and title from the strings.xml file
builder.setMessage("Welcome to Alert Dialog") .setTitle("Dialog Demo");

//Setting message manually and performing action on button click
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
Toast.makeText(getApplicationContext(),"you choose yes action for alertbox",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
Toast.makeText(getApplicationContext(),"you choose no action for alertbox",
Toast.LENGTH_SHORT).show();
}
});
//Creating dialog box
AlertDialog alert = builder.create();
//Setting the title manually
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}

Output