Alert Dialog with SingleItemSelection in Android
Last Updated :
10 Feb, 2025
Alert Dialogs are the UI elements that pop up when the user performs some crucial actions with the application. These window-like elements may contain multiple or single items to select from the list or have the error message and some action buttons. In this article, it’s been discussed how to implement the Alert Dialogs with the single item selection. Look at the following image to differentiate the alert dialogs with action buttons and single item selection. We will implement this project using both Java and Kotlin Programming Languages for Android.
Implementation Alert Dialog with SingleItemSelection
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.
The code for that has been given in both Java and Kotlin Programming Language for Android.
Step 2: Working with the XML Files
Next, go to the activity_main.xml file, which represents the project’s UI. Below is the code for the activity_main.xml file. Comments are added inside the code to help you understand the code in more detail.
activity_main.xml:
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"
android:orientation="vertical"
tools:context=".MainActivity"
tools:ignore="HardcodedText">
<Button
android:id="@+id/openAlertDialogButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:backgroundTint="@android:color/holo_green_dark"
android:text="OPEN ALERT DIALOG"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="@+id/selectedItemPreview"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<TextView
android:id="@+id/selectedItemPreview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Selected Item is: "
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/openAlertDialogButton" />
</androidx.constraintlayout.widget.ConstraintLayout>
Design UI:

Step 3: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity File. Comments are added inside the code to understand the code in more detail. There is a need to understand the parts of the AlertDialog with single item selection.
Have a look at the following image:

Working with the MainActivity File
The function used for implementing the single item selection is setSingleChoiceItems which is discussed below:
Syntax:
alertDialog.setSingleChoiceItems(listItems, checkedItem[0]) { dialog, which ->
}
Parameters:
- listItems: are the items to be displayed on the alert dialog.
- checkedItems: the boolean array maintains the selected values as true and unselected values as false.
- DialogInterface.OnMultiChoiceClickListener(): This is a callback when a change in the selection of items takes place.
Invoke the following code. Comments are added inside the code for better understanding.
Java
package org.geeksforgeeks.demo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private Button bOpenAlertDialog;
private TextView tvSelectedItemPreview;
// Store the selected item index (-1 means no selection by default)
private int selectedItemIndex = -1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bOpenAlertDialog = findViewById(R.id.openAlertDialogButton);
tvSelectedItemPreview = findViewById(R.id.selectedItemPreview);
// List of items to choose from
String[] listItems = {"Android Development", "Web Development", "Machine Learning"};
bOpenAlertDialog.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
// AlertDialog builder instance to build the alert dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this)
.setIcon(R.mipmap.ic_launcher_round)
.setTitle("Choose an Item");
// Build the alert dialog with single-choice items
alertDialog.setSingleChoiceItems(listItems, selectedItemIndex, (dialog, which) -> {
// Update the selected item index
selectedItemIndex = which;
// Update the TextView to show the selected item
tvSelectedItemPreview.setText("Selected Item is:\n" + listItems[which]);
// Dismiss the dialog
dialog.dismiss();
});
// Create and show the AlertDialog
AlertDialog customAlertDialog = alertDialog.create();
customAlertDialog.show();
}
});
}
}
Kotlin
package org.geeksforgeeks.demo
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
private lateinit var bOpenAlertDialog: Button
private lateinit var tvSelectedItemPreview: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bOpenAlertDialog = findViewById(R.id.openAlertDialogButton)
tvSelectedItemPreview = findViewById(R.id.selectedItemPreview)
// single item array instance to store which element
// is selected by user initially it should be set to
// zero meaning none of the element is selected by default
val checkedItem = intArrayOf(-1)
bOpenAlertDialog.setOnClickListener {
// AlertDialog builder instance to build the alert dialog
val alertDialog = AlertDialog.Builder(this)
// set the custom icon to the alert dialog
.setIcon(R.mipmap.ic_launcher_round)
// title of the alert dialog
.setTitle("Choose an Item")
val listItems = arrayOf("Android Development", "Web Development", "Machine Learning")
// the function setSingleChoiceItems is the function which
// builds the alert dialog with the single item selection
alertDialog.setSingleChoiceItems(listItems, checkedItem[0]) { dialog, which ->
// update the selected item which is selected by the
// user so that it should be selected when user opens
// the dialog next time and pass the instance to setSingleChoiceItems method
checkedItem[0] = which
// now also update the TextView which previews the selected item
tvSelectedItemPreview.text = buildString {
append("Selected Item is :\n")
append(listItems[which])
}
// when selected an item the dialog should be closed
// with the dismiss method
dialog.dismiss()
}
// create and build the AlertDialog instance with the
// AlertDialog builder instance
val customAlertDialog = alertDialog.create()
// show the alert dialog when the button is clicked
customAlertDialog.show()
}
}
}
Output:
Similar Reads
Alert Dialog with MultipleItemSelection in Android
In the previous article Alert Dialog with SingleItemSelection in Android, we have seen how the alert dialog is built for single item selection. In this article, it's been discussed how to build an alert dialog with multiple item selection. Multiple Item selection dialogs are used when the user wants
5 min read
How to Set Buttons Inside an Alert Dialog in Android?
In this article, we are going to see how can we set two buttons inside an Alert Dialog. For example, we can see when an alert dialog is pop up then their two types of buttons available one is the Ok or Positive Button another one is Cancel or Negative Button. Alert dialogs are most frequently used i
4 min read
How to Change Alert Dialog Position on Screen in Android?
AlertDialog in Android is an alert message that appears in the form of a pop-up consisting of four elements namely a title, a message, a positive button, and a negative button. The positive and the negative buttons are clickable and can be programmed for performing an action. However, the AlertDialo
2 min read
Create Instruction Dialog in Android
In most android applications, you must have seen that when you open a new app it shows some instructions to users about the features of their application. Here, we are going to implement the same. Here is a sample video of what we are going to build in this application. Note that we will be using Ja
3 min read
How to Make an Alert Dialog Fill Majority of the Screen Size in Android?
An Alert Dialog is a window that appears on the screen to give notifications to the user, make some decisions for the user, or enter some information from the user. An Alert Dialog is generally not full screen, but in this article, we'll be implementing something similar. Building an Alert Dialog:Ti
3 min read
Notifications in Android with Example
Notification is a kind of message, alert, or status of an application (probably running in the background) that is visible or available in the Android's UI elements. This application could be running in the background but not in use by the user. The purpose of a notification is to notify the user ab
7 min read
Offline Speech to Text Without any Popup Dialog in Android
In this article, we are going to implement an offline speech-to-text functionality in our project. It can work both Online and Offline. When there is no internet connectivity, it will use the pre-stored language model from our mobile device, so it didn't recognize much clearly but gave good results.
6 min read
Language Localization in Android with Example
Language Localization is a process of changing the application context into multiple languages based on the requirements. Android is an overall operating system that runs on millions of devices worldwide and among various groups. Since the diversity range is enormous, a feature that facilitates loca
3 min read
How to open dialer in Android through Intent?
The phone dialer is an activity available with the Android operating system to call a number. Usually, such activity may or may not have an EditText, for taking the number as input, and a Call button. When the user presses the Call button, it invokes the dialer app activity. Use of 'tel:' prefix is
3 min read
How to Change the Position of AlertDialog in Android?
AlertDialog in android is one of the UI widgets which immediately pops up to confirm the user interaction or to confirm the action which is done by the user. In most of the applications, the position of the alert dialog is in the center. In this article, it's been discussed how to change the positio
4 min read