Introduction

In this article, we'll learn how to add the alert dialog with setSingleChoiceitems in Android. Let's start with the following procedure.
  1. Start Eclipse IDE.
  2. Create a new project.
  3. Create a MainActivity.java file.
  4. Create an activity_main.xml file for layout design.
  5. Add a Textview field in the XML layout.
  6. Then declare a string array in the MainActivity class like this:

    String[] str={"mp3","Mpeg","wmv","3gp"};

  7. Create an object like this: AlertDialog.Builder aa=new AlertDialog.Builder(this);
  8. With this object add setSingleChoiceItems.
The following is the code.
MainActivity.java
  1. package com.example.alertdialogsetsinglechoice;
  2. import android.app.Activity;
  3. import android.app.AlertDialog;
  4. import android.content.DialogInterface;
  5. import android.content.DialogInterface.OnClickListener;
  6. import android.os.Bundle;
  7. import android.widget.Toast;
  8. public class MainActivity extends Activity {
  9. String[] str = {
  10. "mp3",
  11. "Mpeg",
  12. "wmv",
  13. "3gp"
  14. };
  15. @Override
  16. protected void onCreate(Bundle savedInstanceState) {
  17. super.onCreate(savedInstanceState);
  18. setContentView(R.layout.activity_main);
  19. ffff();
  20. }
  21. public void ffff() {
  22. AlertDialog.Builder aa = new AlertDialog.Builder(this);
  23. aa.setTitle("Choose any one extension type");
  24. aa.setSingleChoiceItems(str, 2, new OnClickListener() {
  25. public void onClick(DialogInterface dialog, int which) {
  26. switch (which) {
  27. case 1:
  28. Toast.makeText(getApplicationContext(), "Hello Abhi, Its mpeg", 100).show();
  29. break;
  30. case 2:
  31. Toast.makeText(getApplicationContext(), "Hello Guyzz ", 100).show();
  32. break;
  33. case 3:
  34. Toast.makeText(getApplicationContext(), "Hello Guyzz ", 100).show();
  35. break;
  36. case 4:
  37. Toast.makeText(getApplicationContext(), "Hello Guyzz ", 100).show();
  38. break;
  39. default:
  40. break;
  41. }
  42. }
  43. });
  44. aa.show();
  45. }
  46. }
activity_main.xml
  1. <RelativeLayout
  2. xmlns:android="http://schemas.android.com/apk/res/android"
  3. xmlns:tools="http://schemas.android.com/tools"
  4. android:layout_width="match_parent"
  5. android:layout_height="match_parent"
  6. android:paddingBottom="@dimen/activity_vertical_margin"
  7. android:paddingLeft="@dimen/activity_horizontal_margin"
  8. android:paddingRight="@dimen/activity_horizontal_margin"
  9. android:paddingTop="@dimen/activity_vertical_margin"
  10. tools:context=".MainActivity" >
  11. <TextView
  12. android:layout_width="wrap_content"
  13. android:layout_height="wrap_content"
  14. android:text="@string/hello_world" />
  15. </RelativeLayout>
Output
Adding Alert Dialog in Andriod