Android alertdialog single choice tutorial

Last Updated on February 6, 2018

Hi and welcome to another tutorial of codingdemos, in this tutorial you will learn how to create android alertdialog single choice. For this tutorial i will be using the same example that i did for android multiple choice list dialog tutorial so be sure to check that out.

  • In this tutorial we will be using the following:
    • Android studio version 2.3.3
    • Android emulator Nexus 5X with API 24
    • Minimum SDK API 16

The final result will look something like this:

  • Open up Android Studio and create a new project and give it a name, in our case we’ve named it (SingleChoiceDialog), choose API 16 as the minimum SDK, then choose blank activity and click on finish and wait for Android Studio to build your project.
  • Open up (activity_main.xml) file and here we will need to add android button which will allow the user to tap on it to show android alertdialog, as well as we need to add android textview which will show the selected item from the android dialog like this:

<?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="wrap_content" 
android:orientation="vertical" 
tools:context="com.codingdemos.singlechoicedialog.MainActivity">

    <Button 
android:id="@+id/button" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_gravity="center" 
android:layout_marginTop="30dp" 
android:text="Tap to see the dialog" />

    <TextView 
android:id="@+id/tvResult" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_gravity="center" 
android:layout_marginTop="30dp" 
android:textColor="@color/colorPrimary" 
android:textSize="25sp" 
android:textStyle="italic" />

</LinearLayout>


  • Now that we are done with adding android button and textview, next is we need to open up (MainActivity.java) file and here is where we need to declare those android views as well as Android alertdialog like this:

Button mButton = (Button) findViewById(R.id.button);
TextView mResult = (TextView) findViewById(R.id.tvResult);

  • Now let’s open up (strings.xml) file and inside this file we need to create a string array that will hold the items of alertdialog, the whole file will look like this:

<resources>
    <string name="app_name">SingleChoiceDialog</string>

    <string-array name="shopping_item">
        <item>Onion</item>
        <item>Sausage</item>
        <item>Milk</item>
        <item>Garlic</item>
        <item>Beef</item>
        <item>Veggies</item>
        <item>Olive</item>
        <item>Cheese</item>
        <item>Tuna</item>
        <item>Mushrooms</item>
    </string-array>
</resources>

  • Inside (MainActivity.java) file we need to declare a variable of type string array and we initialize it with values from shopping items string array like this:

String[] listItems = getResources().getStringArray(R.array.shopping_item);

  • Now to make the button clickable we need to call android button setOnClickListener method like this:

mButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        
    }
});

  • Inside button onClick method we will create our android alertdialog like this:

AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);

  • Next we need to give our alertdialog a title and we do that like this:

mBuilder.setTitle("Choose an item");

  • To be able to allow you to check single item from android alertdialog we need to use android alertdialog setSingleChoiceItems which accept 2 arguments:
    • Items: this is the first value that we need to pass which is list of data that will show up in android alertdialog.
    • CheckedItem: this is the second value that we need to pass which is the number of items that you want them to be checked when showing android alertdialog, if you don’t want any item to be checked you can put (-1).

mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
        
    }
});

  • Inside onClick method of setSingleChoiceItems here we will be able receive any item that was checked and then set that value to our android textview mResult like this:

mResult.setText(listItems[i]);
dialogInterface.dismiss();

  • Once you make a selection from android alertdialog we will set the value to mResult and immediately dismiss alertdialog as shown above.
  • Last thing is we need to show android alertdialog like this:

AlertDialog mDialog = mBuilder.create();
mDialog.show();

  • Here is the full code for (MainActivity.java) file:

package com.codingdemos.singlechoicedialog;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    String[] listItems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listItems = getResources().getStringArray(R.array.shopping_item);

        Button mButton = (Button) findViewById(R.id.button);
        final TextView mResult = (TextView) findViewById(R.id.tvResult);
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
                mBuilder.setTitle("Choose an item");
                mBuilder.setSingleChoiceItems(listItems, -1, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        mResult.setText(listItems[i]);
                        dialogInterface.dismiss();
                    }
                });

                AlertDialog mDialog = mBuilder.create();
                mDialog.show();
            }
        });
    }
}

android alertdialog single choiceFigure (1): Final output

 

  • That’s it we are done for this tutorial 😀

The source code for android alertdialog single choice is available on this link: https://github.com/codingdemos/SingleChoiceDialog

For more cool video please check out the YouTube channel on this link: https://www.youtube.com/c/CodingDemos

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>