CSS Includes

Saturday, January 26, 2013

Android AlertDialog Example with Common User Interface Elements

Ages ago, I posted about a very simple example use of Android AlertDialog. Today I want to share about some more example uses of Android AlertDialog.

In this post, you can see and learn code examples not only about Android AlertDialogs, but also some Android user interface elements like date and time pickers, ListView, ScrollView, form widgets like Checkbox and Radio buttons, EditText and WebView.

Android AlertDialog Example - list of options
You can do more things with
Android AlertDialog. Click to enlarge.

Contents:

          1.0 The Main Activity
          2.0 AlertDialog With Two Buttons
          3.0 AlertDialog With Three Buttons
          4.0 AlertDialog With Time Picker
          5.0 AlertDialog With Date Picker
          6.0 AlertDialog With Simple ListView
          7.0 AlertDialog With ScrollView
          8.0 AlertDialog With Form Element Like EditText , etc.
          9.0 AlertDialog with WebView
          10.0 Code Download

1.0 The MainActivity
In this example, all codes are in one activity only, which is our MainActivity.java

OnCreate Code - This will be our main screen, with buttons that when you click, it will trigger a specific method with AlertDialog.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // activity_main is in res/layout/activity_main.xml
    setContentView(R.layout.activity_main);

    try {

        // Click listener.
        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {

                switch (v.getId()) {

                case R.id.alertTwoBtn:
                    alertTwoButtons();
                    break;

                case R.id.alertThreeBtn:
                    alertThreeButtons();
                    break;

                case R.id.alertTimePickerBtn:
                    alertTimePicker();
                    break;

                case R.id.alertDatePickerBtn:
                    alertDatePicker();
                    break;

                case R.id.alertSimpleListViewBtn:
                    alertSimpleListView();
                    break;

                case R.id.alertScrollViewBtn:
                    alertScrollView();
                    break;

                case R.id.alertFormElementsBtn:
                    alertFormElements();
                    break;

                case R.id.alertWebViewBtn:
                    alertWebView();
                    break;

                }
            }
        };

        // Set button listeners.
        findViewById(R.id.alertTwoBtn).setOnClickListener(handler);
        findViewById(R.id.alertThreeBtn).setOnClickListener(handler);
        findViewById(R.id.alertTimePickerBtn).setOnClickListener(handler);
        findViewById(R.id.alertDatePickerBtn).setOnClickListener(handler);
        findViewById(R.id.alertSimpleListViewBtn).setOnClickListener(
                handler);
        findViewById(R.id.alertScrollViewBtn).setOnClickListener(handler);
        findViewById(R.id.alertFormElementsBtn).setOnClickListener(handler);
        findViewById(R.id.alertWebViewBtn).setOnClickListener(handler);

    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
res/layout/activity_main.xml code
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <Button
        android:id="@+id/alertTwoBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:text="Alert Dialog With Two Buttons" />

    <Button
        android:id="@+id/alertThreeBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertTwoBtn"
        android:text="Alert Dialog With Three Buttons" />

    <Button
        android:id="@+id/alertTimePickerBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertThreeBtn"
        android:text="Alert Dialog With Time Picker" />

    <Button
        android:id="@+id/alertDatePickerBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertTimePickerBtn"
        android:text="Alert Dialog With Date Picker" />

    <Button
        android:id="@+id/alertSimpleListViewBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertDatePickerBtn"
        android:text="Alert Dialog With Simple List View" />

    <Button
        android:id="@+id/alertScrollViewBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertSimpleListViewBtn"
        android:text="Alert Dialog With Scroll View" />

    <Button
        android:id="@+id/alertFormElementsBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertScrollViewBtn"
        android:text="Alert Dialog With Form Elements" />

    <Button
        android:id="@+id/alertWebViewBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/alertFormElementsBtn"
        android:text="Alert Dialog With Web View" />

</RelativeLayout>
Output:
Our main screen.

2.0 Alert Dialog With Two Buttons
Usually used with 'OK' or 'CANCEL', and 'YES' and 'NO' buttons.
/*
 * AlertDialog with two button choices.
 * 
 * We also set the ninja icon here.
 */
public void alertTwoButtons() {
    new AlertDialog.Builder(MainActivity.this)
            .setTitle("Two Buttons")
            .setMessage("Do you think Mike is awesome?")
            .setIcon(R.drawable.ninja)
            .setPositiveButton("YES",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("Thank you! You're awesome too!");
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("NO", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {
                    showToast("Mike is not awesome for you. :(");
                    dialog.cancel();
                }
            }).show();
}
Output:

When the user touched YES.

3.0 Alert Dialog With Three Buttons
You can give users three choices of action, other example can be 'YES', 'NO', and 'CANCEL'. In Android ICS, negative button is always in the left, neutral button is in the center and the yes button is in the right side.
/*
 * AlertDialog with three button choices.
 * 
 * We also set the ninja icon here.
 */
public void alertThreeButtons() {
    new AlertDialog.Builder(MainActivity.this)
            .setTitle("Three Buttons")
            .setMessage("Where do you want to go?")
            .setIcon(R.drawable.ninja)
            .setPositiveButton("RIGHT",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("You want to go to the RIGHT.");

                            dialog.cancel();
                        }
                    })
            .setNeutralButton("CENTER",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("You want to go to the CENTER.");
                            dialog.cancel();
                        }
                    })
            .setNegativeButton("LEFT",
                    new DialogInterface.OnClickListener() {
                        @TargetApi(11)
                        public void onClick(DialogInterface dialog, int id) {
                            showToast("You want to go to the LEFT.");
                            dialog.cancel();
                        }
                    }).show();
}
Output:

When the user touched CENTER.

4.0 Alert Dialog With Time Picker
Another good thing about AlertDialogs is that you can save space on your main UI. You can let users pick the time in the pop up which is simple and beautiful.
/*
 * Show AlertDialog with time picker.
 */
public void alertTimePicker() {

    /*
     * Inflate the XML view. activity_main is in res/layout/time_picker.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.time_picker, null, false);

    // the time picker on the alert dialog, this is how to get the value
    final TimePicker myTimePicker = (TimePicker) view
            .findViewById(R.id.myTimePicker);

    /*
     * To remove option for AM/PM, add the following line:
     * 
     * operatingHoursTimePicker.setIs24HourView(true);
     */

    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(view)
            .setTitle("Set Time")
            .setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

                    String currentHourText = myTimePicker.getCurrentHour()
                            .toString();

                    String currentMinuteText = myTimePicker
                            .getCurrentMinute().toString();

                    // We cannot get AM/PM value since the returning value
                    // will always be in 24-hour format.

                    showToast(currentHourText + ":" + currentMinuteText);

                    dialog.cancel();

                }

            }).show();
}

res/layout/time_picker.xml code:

<?xml version="1.0" encoding="utf-8"?>
<TimePicker xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myTimePicker"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</TimePicker>
Output:


5.0 Alert Dialog With Date Picker
Date pickers on an AlertDialog also save you more space and make date picking enjoyable to the user.
/*
 * Show AlertDialog with date picker.
 */
public void alertDatePicker() {

    /*
     * Inflate the XML view. activity_main is in res/layout/date_picker.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View view = inflater.inflate(R.layout.date_picker, null, false);

    // the time picker on the alert dialog, this is how to get the value
    final DatePicker myDatePicker = (DatePicker) view
            .findViewById(R.id.myDatePicker);

    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(view)
            .setTitle("Set Date")
            .setPositiveButton("Go", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

                    /*
                     * In the docs of the calendar class, January = 0, so we
                     * have to add 1 for getting correct month.
                     * http://goo.gl/9ywsj
                     */
                    int month = myDatePicker.getMonth() + 1;
                    int day = myDatePicker.getDayOfMonth();
                    int year = myDatePicker.getYear();

                    showToast(month + "/" + day + "/" + year);

                    dialog.cancel();

                }

            }).show();
}
res/layout/date_picker.xml code

<DatePicker xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/myDatePicker"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Output:


6.0 Alert Dialog With Simple ListView
I usually do this when I have to give users more than three choices of action.
/*
 * Show AlertDialog with a simple list view.
 * 
 * No XML needed.
 */
public void alertSimpleListView() {

    /*
     * WebView is created programatically here.
     * 
     * @Here are the list of items to be shown in the list
     */
    final CharSequence[] items = { "John", "Michael", "Vincent", "Dalisay" };

    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setTitle("Make your selection");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            // will toast your selection
            showToast("Name: " + items[item]);
            dialog.dismiss();

        }
    }).show();
}
Output:

When the user tapped 'Michael' on the list.

7.0 Alert Dialog With ScrollView
If you want to show long text to the user like your terms of use or privacy policy, you can use a ScrollView with a TextView inside.
/*
 * Show AlertDialog with ScrollView.
 * 
 * We use a TextView as ScrollView's child/host
 */
public void alertScrollView() {

    /*
     * Inflate the XML view.
     * 
     * @activity_main is in res/layout/scroll_text.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View myScrollView = inflater.inflate(R.layout.scroll_text, null, false);

    // textViewWithScroll is the name of our TextView on scroll_text.xml
    TextView tv = (TextView) myScrollView
            .findViewById(R.id.textViewWithScroll);

    // Initializing a blank textview so that we can just append a text later
    tv.setText("");

    /*
     * Display the text 10 times so that it will exceed the device screen
     * height and be able to scroll
     */
    for (int x = 1; x < 50; x++) {
        tv.append("You've been HACKED!\n");
        tv.append("By NINJAZHAI.\n");
        tv.append("Just kidding.\n\n");
    }

    new AlertDialog.Builder(MainActivity.this).setView(myScrollView)
            .setTitle("Scroll View")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
                }

            }).show();

}
res/layout/scroll_text.xml code
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:id="@+id/textViewWithScroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="" />

</ScrollView>
Output:

8.0 Alert Dialog With Form Elements Like EditText, etc.
Here you can also save a lot of space and make your app more simple to use by reducing the number of navigation to forms.
/*
 * Show AlertDialog with some form elements.
 */
public void alertFormElements() {

    /*
     * Inflate the XML view. activity_main is in
     * res/layout/form_elements.xml
     */
    LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    final View formElementsView = inflater.inflate(R.layout.form_elements,
            null, false);

    // You have to list down your form elements
    final CheckBox myCheckBox = (CheckBox) formElementsView
            .findViewById(R.id.myCheckBox);

    final RadioGroup genderRadioGroup = (RadioGroup) formElementsView
            .findViewById(R.id.genderRadioGroup);

    final EditText nameEditText = (EditText) formElementsView
            .findViewById(R.id.nameEditText);

    // the alert dialog
    new AlertDialog.Builder(MainActivity.this).setView(formElementsView)
            .setTitle("Form Elements")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

                    String toastString = "";

                    /*
                     * Detecting whether the checkbox is checked or not.
                     */
                    if (myCheckBox.isChecked()) {
                        toastString += "Happy is checked!\n";
                    } else {
                        toastString += "Happy IS NOT checked.\n";
                    }

                    /*
                     * Getting the value of selected RadioButton.
                     */
                    // get selected radio button from radioGroup
                    int selectedId = genderRadioGroup
                            .getCheckedRadioButtonId();

                    // find the radiobutton by returned id
                    RadioButton selectedRadioButton = (RadioButton) formElementsView
                            .findViewById(selectedId);

                    toastString += "Selected radio button is: "
                            + selectedRadioButton.getText() + "!\n";

                    /*
                     * Getting the value of an EditText.
                     */
                    toastString += "Name is: " + nameEditText.getText()
                            + "!\n";

                    showToast(toastString);

                    dialog.cancel();
                }

            }).show();
}
res/layout/form_elements/xml code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >


    <CheckBox
        android:id="@+id/myCheckBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Happy?" />

    <RadioGroup
        android:id="@+id/genderRadioGroup"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/myCheckBox" >


        <RadioButton
            android:id="@+id/maleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:text="Male" />


        <RadioButton
            android:id="@+id/femaleRadioButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/maleRadioButton"
            android:text="Female" />

    </RadioGroup>



    <EditText
        android:id="@+id/nameEditText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/genderRadioGroup"
        android:ems="10"
        android:hint="Type your name here..." >

        <requestFocus />
    </EditText>

</RelativeLayout>
Output:


9.0 AlertDialog with WebView
Some app that I see put their privacy policy, terms of use and other information to an online page. You can make that AlertDialog with a WebView too.
/*
 * Show AlertDialog with web view.
 * 
 * Don't forget the Internet permission on your AndroidManifest.xml
 */
public void alertWebView() {

    // WebView is created programatically here.
    WebView myWebView = new WebView(MainActivity.this);
    myWebView.loadUrl("http://google.com/");

    /*
     * This part is needed so it won't ask the user to open another browser.
     */
    myWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    });

    new AlertDialog.Builder(MainActivity.this).setView(myWebView)
            .setTitle("My Web View")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                @TargetApi(11)
                public void onClick(DialogInterface dialog, int id) {

                    dialog.cancel();

                }

            }).show();
}
Output:
When webpage is not available.



10.0 Code Download
Android AlertDialog Example download code



Other tips:
If you want to prevent your AlertDialog from cancelling when you touched its button, you have to override the onClickListener of the button.

You can let me know in the comments if you want to correct or add something in this post, thanks!
Thanks for sharing the post! :)
For FREE programming tutorials, enter your email below and subscribe! :)

0 comments:

Post a Comment

You can use http://pastebin.com/ or http://jsfiddle.net/ if you want to comment some codes.

Related Posts