How to create Alert Dialog Box in Android Studio using Java

Android Alert Dialog Box

The Alert Dialog Box widget is a very useful element in Android Studio applications.  You need to use it many times in the App. A Developer has to know how to create and implement an Alert Dialog Box in an Android Application. This Android Studio Tutorial content will help you to know How to create a simple Alert Dialog Box in Android Studio using Java.

For step-by-step implementation you need to follow the following steps-

Step-1: Open Android Studio

Step-2: Create a new project or you can use the existing project 

Step-3: Working with activity_main.xml file

Next, Go to the activity_main.xml file, which is used to display the User Interface of the Android Studio App. The Following codes are for the activity_main.xml file.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<Button
android:id="@+id/AlertButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="300dp"
android:layout_gravity="center_horizontal"
android:backgroundTint="#8DBC03"
android:text="Show Alert Dialog"
android:textSize="20dp"/>

</LinearLayout>

Step-3: Then Work with the MainActivity.java file.

Go to the MainActivity.java File and implement the following code anywhere in the Android project as you wish. You can edit and modify the codes easily. Proper Comments are also added inside the code to understand the code more effectively.

new AlertDialog.Builder(MainActivity.this)
.setIcon(R.drawable.baseline_notification_important_24)
.setTitle("Alert Title goes here")
.setMessage("Alert Message goes here")
.setCancelable(false)
//you can replace cancel with No/Don't Allow/Disagree etc.
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"Dialog Canceled",Toast.LENGTH_SHORT).show();
}
})
// If needed you can use the following Codes
.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"Dialog Neutral",Toast.LENGTH_SHORT).show();
}
})
//you can replace Yes with Ok/Allow/Agree etc.
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this,"OK",Toast.LENGTH_LONG).show();
}
})
.show();

For better practice, you should watch "How to Create a Simple Alert Dialog Box in Android Studio using Java". You can also comment below if you have any queries. Android Alert Dialog Box detailed code is given for your practice. You can use, edit, and modify it.

0 Comments