activity_main.xml
<?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">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Close app"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package com.example.alert_dialog;
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 {
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 view) {
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() {
@Override
public void onClick(DialogInterface dialogInterface, int
id) {
dialogInterface.cancel();
Toast.makeText(getApplicationContext(), "you choose
no action for alertbox",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert= builder.create();
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}