Alert Dialog Window with radio buttons in Android

July 6, 2012
By

The objective of this article is to create an Android application which demonstrates how to create and open an alert dialog window in an application. The key classes that we are using in this application are DialogFragment and AlertDialog. In this article, the alert dialog window will be opened when the button “Choose Android” is selected from the main activity. In the alert dialog window, the set of Android versions will be listed along with radio buttons. User can pick one version and click “OK” button. Then the selected version will be displayed in the main  activity screen. In this application, in order to avoid the coupling between the main activity and the alert dialog, the click listener for the “OK” button is written in the main activity.


1. Create an Android project namely “AlertDialogRadio”

New Android Project

Figure 1 : New Android Project


2. Select Android build target

Select Android Build Target

Figure 2 : Select Android Build Target


3. Enter application details

Enter Application Details

Figure 3 : Enter Application Details


4. res/values/strings.xml


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

    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">AlertDialogRadio</string>
    <string name="str_btn_choose">Choose Android</string>

</resources>


5. res/layout/main.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:padding="40dp"
    />

    <Button
        android:id="@+id/btn_choose"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/str_btn_choose"
        android:layout_gravity="center_horizontal"
    />
</LinearLayout>

  • This is the layout file for the main activity

6. src/in/wptrafficanalyzer/alertdialogradio/Android.java


package in.wptrafficanalyzer.alertdialogradio;
public class Android {
    static String[] code = new String[]{
        "Jelly Bean",
        "Ice Cream Sandwich",
        "Honeycomb",
        "Gingerbread",
        "Froyo",
        "Eclair",
        "Donut",
        "Cupcake"
    };
}
  • This class is used to statically store the list of Android versions

7. src/in/wptrafficanalyzer/alertdialogradio/AlertDialogRadio.java


package in.wptrafficanalyzer.alertdialogradio;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;

public class AlertDialogRadio  extends DialogFragment{

    /** Declaring the interface, to invoke a callback function in the implementing activity class */
    AlertPositiveListener alertPositiveListener;

    /** An interface to be implemented in the hosting activity for "OK" button click listener */
    interface AlertPositiveListener {
        public void onPositiveClick(int position);
    }

    /** This is a callback method executed when this fragment is attached to an activity.
    *  This function ensures that, the hosting activity implements the interface AlertPositiveListener
    * */
    public void onAttach(android.app.Activity activity) {
        super.onAttach(activity);
        try{
            alertPositiveListener = (AlertPositiveListener) activity;
        }catch(ClassCastException e){
            // The hosting activity does not implemented the interface AlertPositiveListener
            throw new ClassCastException(activity.toString() + " must implement AlertPositiveListener");
        }
    }

    /** This is the OK button listener for the alert dialog,
     *  which in turn invokes the method onPositiveClick(position)
     *  of the hosting activity which is supposed to implement it
    */
    OnClickListener positiveListener = new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            AlertDialog alert = (AlertDialog)dialog;
            int position = alert.getListView().getCheckedItemPosition();
            alertPositiveListener.onPositiveClick(position);
        }
    };

    /** This is a callback method which will be executed
     *  on creating this fragment
     */
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        /** Getting the arguments passed to this fragment */
        Bundle bundle = getArguments();
        int position = bundle.getInt("position");

        /** Creating a builder for the alert dialog window */
        AlertDialog.Builder b = new AlertDialog.Builder(getActivity());

        /** Setting a title for the window */
        b.setTitle("Choose your version");

        /** Setting items to the alert dialog */
        b.setSingleChoiceItems(Android.code, position, null);

        /** Setting a positive button and its listener */
        b.setPositiveButton("OK",positiveListener);

        /** Setting a positive button and its listener */
        b.setNegativeButton("Cancel", null);

        /** Creating the alert dialog window using the builder class */
        AlertDialog d = b.create();

        /** Return the alert dialog window */
        return d;
    }
}

  • This is the DialogFragment class which creates AlertDialog window on executing the callback method “onCreateWindow()”

8. src/in/wptrafficanalyzer/alertdialogradio/MainActivity.java


package in.wptrafficanalyzer.alertdialogradio;

import in.wptrafficanalyzer.alertdialogradio.AlertDialogRadio.AlertPositiveListener;
import android.app.Activity;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/** Since this class attaches the dialog fragment "AlertDialogRadio",
*  it is suppose to implement the interface "AlertPositiveListener"
*/
public class MainActivity extends Activity implements AlertPositiveListener {
    /** Stores the selected item's position */
    int position = 0;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        OnClickListener listener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                /** Getting the fragment manager */
                FragmentManager manager = getFragmentManager();

                /** Instantiating the DialogFragment class */
                AlertDialogRadio alert = new AlertDialogRadio();

                /** Creating a bundle object to store the selected item's index */
                Bundle b  = new Bundle();

                /** Storing the selected item's index in the bundle object */
                b.putInt("position", position);

                /** Setting the bundle object to the dialog fragment object */
                alert.setArguments(b);

                /** Creating the dialog fragment object, which will in turn open the alert dialog window */
                alert.show(manager, "alert_dialog_radio");
            }
        };

        /** Getting the reference of the button from the main layout */
        Button btn = (Button) findViewById(R.id.btn_choose);

        /** Setting a button click listener for the choose button */
        btn.setOnClickListener(listener);
    }

    /** Defining button click listener for the OK button of the alert dialog window */
    @Override
    public void onPositiveClick(int position) {
        this.position = position;

        /** Getting the reference of the textview from the main layout */
        TextView tv = (TextView) findViewById(R.id.tv_android);

        /** Setting the selected android version in the textview */
        tv.setText("Your Choice : " + Android.code[this.position]);
    }
}

  • This is the main activity file, from where the alert dialog window is invoked.

9. The application in execution

This is the main activity

Figure 4 : The main activity screen on launching the application

Alert Dialog Window

Figure 5 : Opens this alert dialog window on clicking the "Choose" button

Main Activity after the selection

Figure 6 : Main Activity screen after the selection of Android Version


10. Download


11. Reference

http://developer.android.com/guide/index.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , ,

7 Responses to Alert Dialog Window with radio buttons in Android

  1. Chris on September 19, 2012 at 10:21 pm

    Thanks for the example, but posting code samples when the content width is so small, is annoying. ;)

    • george on September 20, 2012 at 12:17 pm

      Thanks for your suggestion

  2. Elijah Keya on October 12, 2012 at 1:19 pm

    Thanks George for your example. After clicking “Jelly Bean” under “choose your version”, can it take you to a textfield whereby yo can write something about “Jelly Bean” and “Send”

    cheers

  3. Akshay on October 3, 2013 at 5:49 pm

    Can you similar that can work for both 2.3 and 4.0?

  4. maniteja on September 4, 2014 at 4:30 pm

    The above example which was provided by you helped me alot and i need some help that in place of textview i am displaying the custom listview in the above example and i need the position of listview as well as the position of radiobuttons.can you help me regarding this?

  5. Sateesh Reddy on February 6, 2015 at 6:52 pm

    Hi George

    The article is very useful.

    If there is a need of more than one Alert Dialog in same screen, how to call different onPositiveClick functions.

  6. Arnab on September 25, 2015 at 4:30 pm

    Its realy helpful thanks a lot @George Mathew

Leave a Reply to Chris Cancel reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner