Android options dialog

In your application, you might want to display a dialog of multiple options. For example a color chooser dialog displays a list of colors from which one color is selected as the background of the activity.

To create a dialog, you use the Dialog class. A dialog can have its own layout file. In the layout, you define RadioButtons to display on the dialog. To perform an action when a RadioButton on the dialog is selected, in code, you need to register the RadioButton with onCheckedChangeListener interface and override the onCheckedChanged method.

Now to have an example application on creating options dialog, you create a new project. Then in the res/layout directory, you create a layout file called dialog_layout.xml. In the layout, there is one RadioGroup. In the RadioGroup, there are three RadioButtons that corresponds to while, blue, and green color options.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android= ""
     android:layout_height="wrap_content" >



In onCreate() method of the MainActivity class, you write the following code to create a Dialog instance, set layout to the dialog using setContentView() method, register each RadioButton with the onCheckedChangeListener to perform an action when the RadioButton is selected.

protected void onCreate(Bundle savedInstanceState) {
     // Create dialog instance
     Dialog dialog = new Dialog(this);
     // Set dialog title
     dialog.setTitle("Background Color");
     // Set dialog layout that contains radio buttons
     RadioGroup radioGroup = (RadioGroup) dialog.findViewById(;

     // Register radio buttons to receive change event
     for(int i=0; i<radioGroup.getChildCount(); ++i){
        RadioButton radio = (RadioButton)radioGroup.getChildAt(i);
        radio.setOnCheckedChangeListener(new OnCheckedChangeListener() {
           public void onCheckedChanged(CompoundButton cb, boolean b) {
             if (b) {
                String selectedColor=cb.getText().toString();
                else if(selectedColor.equals("Blue"))

     // Display the dialog;


Posted by: Dara | post date: 02-26-2015 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.