Open In App

Alert Dialog with SingleItemSelection in Android

Last Updated : 30 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Alert Dialog with SingleItemSelection in Android

Step by Step Implementation

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 UI of the project. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML




<?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"
    tools:ignore="HardcodedText">
  
    <Button
        android:id="@+id/openAlertDialogButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="64dp"
        android:text="OPEN ALERT DIALOG"
        android:textSize="18sp" />
  
    <TextView
        android:id="@+id/selectedItemPreview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:text="Selected Item is: "
        android:textSize="18sp" />
</LinearLayout>


Output UI:

Alert Dialog with SingleItemSelection in Android

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:

Alert Dialog with SingleItemSelection in Android

The function used for implementing the single item selection is setSingleChoiceItems which is discussed below:

Syntax:

setSingleChoiceItems (listItems, checkedItem[0], DialogInterface.OnClickListener listener){}

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




import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
  
public class MainActivity extends AppCompatActivity {
  
    // Button and TextView instances
    Button bOpenAlertDialog;
    TextView tvSelectedItemPreview;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
        // register both UI elements with their appropriate IDs.
        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
        final int[] checkedItem = {-1};
  
        // handle the button to open the alert dialog with the single item selection when clicked
        bOpenAlertDialog.setOnClickListener(v -> {
            // AlertDialog builder instance to build the alert dialog
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
  
            // set the custom icon to the alert dialog
            alertDialog.setIcon(R.drawable.image_logo);
  
            // title of the alert dialog
            alertDialog.setTitle("Choose an Item");
  
            // list of the items to be displayed to the user in the 
            // form of list so that user can select the item from
            final String[] listItems = new String[]{"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.setText("Selected Item is : " + listItems[which]);
  
                // when selected an item the dialog should be closed with the dismiss method
                dialog.dismiss();
            });
  
            // set the negative button if the user is not interested to select or change already selected item
            alertDialog.setNegativeButton("Cancel", (dialog, which) -> {
  
            });
  
            // create and build the AlertDialog instance with the AlertDialog builder instance
            AlertDialog customAlertDialog = alertDialog.create();
  
            // show the alert dialog when the button is clicked
            customAlertDialog.show();
        });
    }
}


Kotlin




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() {
  
    // Button and TextView instances
    lateinit var bOpenAlertDialog: Button
    lateinit var tvSelectedItemPreview: TextView
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // register both UI elements with their appropriate IDs.
        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)
  
        // handle the button to open the alert dialog with the single item selection when clicked
        bOpenAlertDialog.setOnClickListener {
            // AlertDialog builder instance to build the alert dialog
            val alertDialog = AlertDialog.Builder(this)
  
            // set the custom icon to the alert dialog
            alertDialog.setIcon(R.drawable.image_logo)
  
            // title of the alert dialog
            alertDialog.setTitle("Choose an Item")
  
            // list of the items to be displayed to the user in the
            // form of list so that user can select the item from
            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.setText("Selected Item is : " + listItems[which])
  
                // when selected an item the dialog should be closed with the dismiss method
                dialog.dismiss()
            }
  
            // set the negative button if the user is not interested to select or change already selected item
            alertDialog.setNegativeButton("Cancel") { dialog, which -> }
  
            // 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: Run on Emulator



Similar Reads

How to Create an Alert Dialog Box in Android?
Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the message to warn you and then according to your response, the next step is processed. Android Alert Dialog is built with the use of three fields: Title, Message area, and Action Button. Alert Dialog code has three methods:setTitle() method f
4 min read
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 to select multiple items at a time. Have a look a
5 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 AlertDialog appears in the center of the screen whenever cal
2 min read
How to Close Alert Dialog Box in Android Programmatically?
AlertDialog is a flash or an alert message with options that let the user proceed or deny any process or action. AlertDialog generally consists of the main title, the message, and two buttons, technically termed as a positive button and a negative button. Both positive and negative buttons can be programmed to perform various actions. By default, t
2 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:Title: This area gives title to the alert dialog Des
3 min read
How to Add a Third Button to an Android Alert Dialog?
An Alert Dialog in Android is a small window that pops up on the screen to display important information, warnings, or confirmations to the user. It can be used to prompt the user for input, provide a message, or display an error. Step by Step Implementation Step 1: Create a New Project in Android Studio To create a new project in Android Studio pl
3 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 in Android applications to display information to t
4 min read
How to Create AlertDialog Box Using SweetAlert Dialog Library in Android?
In this article, we will learn about how to add Custom Alert Dialog in an app using the SweetAlert Dialog Library. It is a pop-up box that appears in response to any action of the user. AlertBox is very useful when it comes to validation, it can be used to display confirmation messages. Suppose the user presses the Back Button without saving the ch
3 min read
Set MIN and MAX Selectable Dates in DatePicker Dialog in Android
Applications like ticket booking for traveling, theatres, movies, plays, appointments, reminders, etc., require the user to pick a specific day or time for confirming a slot or a booking. In most of these applications, a service is to be picked and then the user has to pick up a slot to further proceed. At this point, while picking up a date, the c
4 min read
How to Create Dynamic Bottom Sheet Dialog in Android using Firebase Firestore?
Bottom Sheet Dialog is one of the famous Material UI Component which is used to display the data or notifications in it. We can display any type of data or any UI component in our Bottom Sheet Dialog. In this article, we will take a look at the implementation of dynamic Bottom Sheet Dialog in Android using Firebase Firestore. What we are going to b
7 min read
Practice Tags :