Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Alert Dialog with SingleItemSelection in Android

  • Last Updated : 12 Nov, 2021

Alert Dialogs are the UI elements that pop up when the user performs some crucial actions with the application. These are the window like elements that may contain multiple or single items to select from the list or it may 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. Have a look at the following image to differentiate the alert dialogs with action buttons and single item selection. Note that we are going to implement this project using the Java language. 

Alert Dialog with SingleItemSelection in Android

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!

Steps to implement the Alert Dialog with the Single Item Selection

Step 1: Create an empty activity Android Studio project

Step 2: Working with the activty_main.xml file



  • In the activity_main.xml which contains one button and TextView. Button to open alert dialog with a single item selection list. And text view which previews the selected item, which is selected by the user.
  • Invoke the following layout code inside the activity_main.xml file, which contains only one Button and TextView element.

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    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.java file

  • 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 deisplayed on the alert dialog.

checkedItems: it is the boolean array which maintains the selected values as true, and unselected values as false.

DialogInterface.OnMultiChoiceClickListener(): which is callback when 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.annotation.SuppressLint;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
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(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);
  
                // 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], new DialogInterface.OnClickListener() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onClick(DialogInterface dialog, int 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", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int 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();
            }
        });
    }
}

Output: Run on Emulator




My Personal Notes arrow_drop_up