How To Scroll Android TextView

Hi there! Today we’re going to do a script that will make a scrolling Android TextView. I found this one useful when I’m testing my other code snippets. The situation is, my text output exceeds the height of my android device screen, I cannot see the whole output unless I make the TextView scrolling.

Let’s rock and scroll! :))

Let’s rock and scroll! :))

We will have the following code on our main activity – ScrollingTextView.java

package com.example.ScrollingTextView;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ScrollingTextView extends Activity {
    TextView tv;
    
    //Called when the activity is first created. 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        //textViewWithScroll is the name of our TextView on main.xml
        this.tv = (TextView) this.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 < 11; x++ ){
            tv.append("Hi there!n");
            tv.append("Did you know that...n");
            tv.append("I'm handsome? Hahaha! Just kidding.n");
        }
    }
}

And then the following codes on our layout file – main.xml

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

    <ScrollView   
    android:id="@+id/ScrollView01"  
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:layout_below="@+id/DownloadData" >  
    
        <TextView  
        android:text="Text here..."
        android:id="@+id/textViewWithScroll" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent"/>
        
    </ScrollView>  
    
</RelativeLayout>

We will have something like this on the output:droidscroll

Thanks for reading this How To Scroll Android TextView!

14+ Android AlertDialog.Builder Example Codes and Output

Android AlertDialog.Builder Example

These Android AlertDialog.Builder example codes are some of the most common UI element or widget that we use with any Android app. In general, an AlertDialog is a small window that appears in front of your application. It gets the screen focus and able to accept user interaction.

Dialogs are normally used for notifications that should interrupt the user and to perform short tasks.

In this post, we are going to take a look at some common types of AlertDialog I use during Android development. We will cover how to show an Android AlertDialog – from basic to a little complex type.

We will cover the following topics or contents:

1.0 Demo Video

2.0 How to run one of the examples?

3.0 Android AlertDialog Examples
3.1 Android AlertDialog with OK Button
3.2 Android AlertDialog with OK and Cancel Button
3.3 Android AlertDialog with Three Buttons
3.4 Android AlertDialog with Time Picker
3.5 Android AlertDialog with Date Picker
3.6 Android AlertDialog with ListView
3.7 Android AlertDialog with ScrollView
3.8 Android AlertDialog with EditText
3.9 Android AlertDialog with WebView
3.10 Android AlertDialog with Customized Layout
3.11 Android AlertDialog with Single Choice
3.12 Android AlertDialog with Multiple Choices
3.13 AlertDialog with EditText and Soft-Keyboard Shown Automatically
3.14 Persistent AlertDialog

4.0 Tips and Suggestions

5.0 Links and Literature
5.1 Source Code Downloads
5.2 Android AlertDialog Online Resources
5.3 The Code of a Ninja Resources

1.0 Android AlertDialog.Builder Example – Demo Video

First, I want you to see what will be the final output of our code for today. Here’s a video demo I shoot for you guys.

2.0 How to run one of the examples?

Here’s a very simple code to run one of the example methods.

package com.example.alertdialogoneexample;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;

public class MainActivity extends Activity {

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

        alertOneButton();

    }

    /*
     * AlertDialog with one action button.
     */
    public void alertOneButton() {

        new AlertDialog.Builder(MainActivity.this)
                .setTitle("One Button")
                .setMessage("Thanks for visiting The Code of a Ninja - codeofaninja.com")
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                        dialog.cancel();
                    }
                }).show();
    }

}

When you run the code above, it will look like this…

Android AlertDialog.Builder Example - how to run one of the example alertdialog methods

On the following examples – numbers 3.0 to 16.0, the presentation will look like this: Code and then output.

3.0 List of Android AlertDialog.Builder Example Codes and Screenshots

3.1 Android AlertDialog with OK Button

You can always change the button’s label by changing setPositiveButton’s first parameter, from “OK” to whatever characters or label you want. By the way, showToast() is another method I used to show a temporary or short lived message prompt to the user.

/*
 * AlertDialog with one button.
 */
public void alertOneButton() {

    new AlertDialog.Builder(MainActivity.this)
            .setTitle("One Button")
            .setMessage("The Code of a Ninja is your new favorite website.")
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    showToast("Thank you!");
                    dialog.cancel();
                }
            }).show();
}

Output:

android alertdialog with ok button

3.2 Android AlertDialog OK Cancel Example

The ninja icon was set using the setIcon() with image from the project’s drawable resource.

/*
 * 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:

android alertdialog ok cancel example

3.3 Android AlertDialog with Three Buttons

As you can see, the positive button is located on the left side. The neutral button is always in the center and the negative 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:

android alertdialog with three buttons

3.4 Android AlertDialog with TimePicker

The TimePicker in our example were inflated from a layout resource. You can also do this programatically but I recommend using an XML layout resource so your TimePicker can be reused and easily themed.

/*
 * 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

<?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:

android alertdialog with timepicker

3.5 Android AlertDialog with DatePicker

Keep in mind that we’re using a DatePicker XML layout resource here, we called it date_picker.xml, code were also provided below.

/*
 * 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);
    
    // so that the calendar view won't appear
    myDatePicker.setCalendarViewShown(false);
    
    // 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:

android alertdialog with datepicker

Not looking good right? The view above is suitable for tablets only and not for phone screens, so we have to disable the calendar view using DatePicker’s setCalendarViewShown() method. Here’s something better for smartphones.

android alertdialog with datepicker 2

3.6 AlertDialog With Simple ListView

You can add or remove items inside the CharSequence[] items. You can set the actions inside the onClick(), with the help of if-else statement.

/*
 * 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();
}

alertdialog with simple listview

3.7 AlertDialog With ScrollView

It can be achieved using the code below with an XML layout resource with a TextView wrapped inside a ScrollView widge. See scroll_text.xml code also provided below.

/*
 * 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:

android alertdialog with scrollview

3.8 Android AlertDialog EditText, etc.

We also inflated an XML layout resource called form_elements.xml, code were also provided below.

/*
 * 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

<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:

android alertdialog with edittext

3.9 AlertDialog with WebView

You can simply specify any web page inside the WebView’s loadUrl() method.

/*
 * 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:

android alertdialog with webview

3.10 AlertDialog with Customized Layout

Used when you don’t want an AlertDialog look like the usual. Again, the key to this is to make your customized XML resource and then inflate it!

public void alertCustomizedLayout(){
    
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

    // get the layout inflater
    LayoutInflater inflater = MainActivity.this.getLayoutInflater();

    // inflate and set the layout for the dialog
    // pass null as the parent view because its going in the dialog layout
    builder.setView(inflater.inflate(R.layout.login, null))
    
    // action buttons
    .setPositiveButton("Login", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // your sign in code here
        }
    })
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // remove the dialog from the screen
        }
    })
    .show();  
    
}

res/layout/login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="64dp"
        android:background="#d1d1d1"
        android:contentDescription="@string/app_name"
        android:scaleType="center"
        android:src="@drawable/ninja" />

    <EditText
        android:id="@+id/username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="4dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="16dp"
        android:hint="Username"
        android:inputType="textEmailAddress" />

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="16dp"
        android:layout_marginLeft="4dp"
        android:layout_marginRight="4dp"
        android:layout_marginTop="4dp"
        android:fontFamily="sans-serif"
        android:hint="Password"
        android:inputType="textPassword" />

</LinearLayout>

Output:

alertdialog with customized layout

3.11 AlertDialog with Single Choice Item

Please note that we used setSingleChoiceItems() below to create the list with radio and two action buttons. You can also make it to three action buttons by adding a neutral button.

Also, a string resource was used. R.array.choices contains the items in the list, it can be found in your strings.xml. If you want to use an array adapter because you have a list from other resource such as a database, you can use this with the help of my other post.

public void alertSingleChoiceItems(){
    
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    
    // Set the dialog title
    builder.setTitle("Choose One")
    
    // specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive call backs when items are selected
    // again, R.array.choices were set in the resources res/values/strings.xml
    .setSingleChoiceItems(R.array.choices, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            showToast("Some actions maybe? Selected index: " + arg1);
        }

    })
           
     // Set the action buttons
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // user clicked OK, so save the mSelectedItems results somewhere
            // or return them to the component that opened the dialog
            
            int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
            showToast("selectedPosition: " + selectedPosition);
            
        }
    })
    
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // removes the dialog from the screen
            
        }
    })
    
    .show();
    
}

res/values/strings.xml

<resources>

    <string name="app_name">TestApp</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">TestApp</string>
    <string name="showTimeDialogFrom">showTimeDialogFrom</string>

    <string-array name="choices">
        <item>Coke</item>
        <item>Pepsi</item>
        <item>Sprite</item>
        <item>Seven Up</item>
    </string-array>

</resources>

alertdialog with single choice item

3.12 AlertDialog with Multiple Choice Item

Used for giving users a chance to pick multiple items on a list.

This time, we used the dialog builder’s setMultiChoiceItems() method but the items in the list is still the one of strings.xml. The onClick() method is responsible for adding or removing selected items which is stored in the mSelectedItems variable.

By the way, mSelectedItems variable were declared as a property variable of our class MainActivity. The AlertDialog above can be achieved with the following code.



public void alertMultipleChoiceItems(){
    
    // where we will store or remove selected items
    mSelectedItems = new ArrayList<Integer>();  
    
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    
    // set the dialog title
    builder.setTitle("Choose One or More")
    
    // specify the list array, the items to be selected by default (null for none),
    // and the listener through which to receive call backs when items are selected
    // R.array.choices were set in the resources res/values/strings.xml
    .setMultiChoiceItems(R.array.choices, null, new DialogInterface.OnMultiChoiceClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
            
            if (isChecked) {
                // if the user checked the item, add it to the selected items
                mSelectedItems.add(which);
            } 
        
            else if (mSelectedItems.contains(which)) {
                // else if the item is already in the array, remove it 
                mSelectedItems.remove(Integer.valueOf(which));
            }
            
            // you can also add other codes here, 
            // for example a tool tip that gives user an idea of what he is selecting
            // showToast("Just an example description.");
        }

    })
           
     // Set the action buttons
    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            
            // user clicked OK, so save the mSelectedItems results somewhere
            // here we are trying to retrieve the selected items indices
            String selectedIndex = "";
            for(Integer i : mSelectedItems){
                selectedIndex += i + ", ";
            }
            
            showToast("Selected index: " + selectedIndex);
        
        }
    })
    
    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // removes the AlertDialog in the screen
        }
    })
    
    .show();
    
}

The strings.xml used in this example is the same with the # 11.0 above.

Output:

alertdialog with multiple choice item

3.13 AlertDialog with EditText and Soft-Keyboard Shown Automatically

When you have an EditText inside an AlertDialog, the EditText can be focused but it won’t show the keyboard automatically. The user has to tap the EditText first, which can be annoying.

The following code will make the Soft-keyboard automatically shown.

public void alertEditTextKeyboardShown(){
    
    // creating the EditText widget programatically
    EditText editText = new EditText(MainActivity.this);
    
    // create the AlertDialog as final
    final AlertDialog dialog = new AlertDialog.Builder(MainActivity.this)
        .setMessage("You are ready to type")
        .setTitle("The Code of a Ninja")
        .setView(editText)
        
         // Set the action buttons
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int id) {
                
            }
        })
        
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            // removes the AlertDialog in the screen
            }
        })
        .create();
    
    // set the focus change listener of the EditText
    // this part will make the soft keyboard automaticall visible
    editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
            }
        }
    });
    
    dialog.show();

}

Output:

alertdialog-with-edittext-and-soft keyboard shown automatically

3.14 Preventing AlertDialog from Closing when a Button is Clicked

Commonly used when your AlertDialog have some sort of validation. It is a default behaviour of an AlertDialog to be closed when one of its action button was clicked. To prevent that, we have to make it persistent by overriding the DialogInterface.

See the following very useful piece of code.

public void alertPersistentDialog(){
    
    final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this)
        .setTitle("The Code of a Ninja")
        .setMessage("This is a persistent AlertDialog")
        .setPositiveButton("Show Toast", null) // null to override the onClick
        .setNegativeButton("Dismiss", null)
        .setCancelable(false)
        .create();

    alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {

        @Override
        public void onShow(DialogInterface dialog) {

            Button btnPositive = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            btnPositive.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {

                    showToast("Dialog not dismissed!");
                    
                }
            });
            
            
            Button btnNegative = alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
            btnNegative.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View view) {

                    // dismiss once everything is ok
                    alertDialog.dismiss();
                }
            });
        }
    });
    
    // don't forget to show it
    alertDialog.show();
        
}

Output:

preventing alertdialog from closing when a button is clicked

4.0 Tips and Suggestions

If you want to add more views or widgets inside an Android AlertDialog, you can just simply inflate it. You can use the code examples above as your reference.

If you want to see the complete code of the project, I recommend downloading the whole source code. There you can see not only the MainActivity but also the layout resources, string resources and the AndroidManifest.xml, the code examples above were just for our quick reference.

Should you want to add your awesome Android AlertDialog example in this list, you can just submit it to my email ninjazhai30(at)gmail(dot)com

5.0 Links and Literature

5.1 Source Code Downloads

You can get the source code by following the whole, well detailed and free tutorial above. But isn’t it more convenient if you can just download the complete source code we used, and play around it?

There’s a small fee in getting the complete source code, it is small compared to the:

✔ Value or skill upgrade it can bring you, or YES
✔ Income you can get from your website project or business. YES
✔ Precious time you save. YES

Buy now

5.2 Android AlertDialog Online Resources

Android AlertDialog Class
Android Dialogs
Building an AlertDialog from the Official Android Docs
How to create a Dialog without a title?
How to change theme for AlertDialog?
How to show AlertDialog in any position of the screen?

If you think we missed any essential Android AlertDialog.Builder Example, please tell us by dropping a comment below! We want this list to be a one stop page or reference for these types of example codes. Thanks!