How can I display a list view in an Android Alert Dialog? How can I display a list view in an Android Alert Dialog? android android

How can I display a list view in an Android Alert Dialog?


Used below code to display custom list in AlertDialog

AlertDialog.Builder builderSingle = new AlertDialog.Builder(DialogActivity.this);builderSingle.setIcon(R.drawable.ic_launcher);builderSingle.setTitle("Select One Name:-");final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(DialogActivity.this, android.R.layout.select_dialog_singlechoice);arrayAdapter.add("Hardik");arrayAdapter.add("Archit");arrayAdapter.add("Jignesh");arrayAdapter.add("Umang");arrayAdapter.add("Gatti");builderSingle.setNegativeButton("cancel", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                dialog.dismiss();            }        });builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                String strName = arrayAdapter.getItem(which);                AlertDialog.Builder builderInner = new AlertDialog.Builder(DialogActivity.this);                builderInner.setMessage(strName);                builderInner.setTitle("Your Selected Item is");                builderInner.setPositiveButton("Ok", new DialogInterface.OnClickListener() {                            @Override                            public void onClick(DialogInterface dialog,int which) {                                dialog.dismiss();                            }                        });                builderInner.show();            }        });builderSingle.show();


According to the documentation, there are three kinds of lists that can be used with an AlertDialog:

  1. Traditional single-choice list
  2. Persistent single-choice list (radio buttons)
  3. Persistent multiple-choice list (checkboxes)

I will give an example of each below.

Traditional single-choice list

The way to make a traditional single-choice list is to use setItems.

enter image description here

Java version

// setup the alert builderAlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setTitle("Choose an animal");// add a listString[] animals = {"horse", "cow", "camel", "sheep", "goat"};builder.setItems(animals, new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        switch (which) {            case 0: // horse            case 1: // cow            case 2: // camel            case 3: // sheep            case 4: // goat        }    }});// create and show the alert dialogAlertDialog dialog = builder.create();dialog.show();

There is no need for an OK button because as soon as the user clicks on a list item control is returned to the OnClickListener.

Kotlin version

// setup the alert builderval builder = AlertDialog.Builder(context)builder.setTitle("Choose an animal")// add a listval animals = arrayOf("horse", "cow", "camel", "sheep", "goat")builder.setItems(animals) { dialog, which ->    when (which) {        0 -> { /* horse */ }        1 -> { /* cow   */ }        2 -> { /* camel */ }        3 -> { /* sheep */ }        4 -> { /* goat  */ }    }}// create and show the alert dialogval dialog = builder.create()dialog.show()

Radio button list

enter image description here

The advantage of the radio button list over the traditional list is that the user can see what the current setting is. The way to make a radio button list is to use setSingleChoiceItems.

Java version

// setup the alert builderAlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setTitle("Choose an animal");// add a radio button listString[] animals = {"horse", "cow", "camel", "sheep", "goat"};int checkedItem = 1; // cowbuilder.setSingleChoiceItems(animals, checkedItem, new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        // user checked an item    }});// add OK and Cancel buttonsbuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        // user clicked OK    }});builder.setNegativeButton("Cancel", null);// create and show the alert dialogAlertDialog dialog = builder.create();dialog.show();

I hard coded the chosen item here, but you could keep track of it with a class member variable in a real project.

Kotlin version

// setup the alert builderval builder = AlertDialog.Builder(context)builder.setTitle("Choose an animal")// add a radio button listval animals = arrayOf("horse", "cow", "camel", "sheep", "goat")val checkedItem = 1 // cowbuilder.setSingleChoiceItems(animals, checkedItem) { dialog, which ->    // user checked an item}// add OK and Cancel buttonsbuilder.setPositiveButton("OK") { dialog, which ->    // user clicked OK}builder.setNegativeButton("Cancel", null)// create and show the alert dialogval dialog = builder.create()dialog.show()

Checkbox list

enter image description here

The way to make a checkbox list is to use setMultiChoiceItems.

Java version

// setup the alert builderAlertDialog.Builder builder = new AlertDialog.Builder(context);builder.setTitle("Choose some animals");// add a checkbox listString[] animals = {"horse", "cow", "camel", "sheep", "goat"};boolean[] checkedItems = {true, false, false, true, false};builder.setMultiChoiceItems(animals, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {    @Override    public void onClick(DialogInterface dialog, int which, boolean isChecked) {        // user checked or unchecked a box    }});// add OK and Cancel buttonsbuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {    @Override    public void onClick(DialogInterface dialog, int which) {        // user clicked OK    }});builder.setNegativeButton("Cancel", null);// create and show the alert dialogAlertDialog dialog = builder.create();dialog.show();

Here I hard coded the the which items in the list were already checked. It is more likely that you would want to keep track of them in an ArrayList<Integer>. See the documentation example for more details. You can also set the checked items to null if you always want everything to start unchecked.

Kotlin version

// setup the alert builderval builder = AlertDialog.Builder(context)builder.setTitle("Choose some animals")// add a checkbox listval animals = arrayOf("horse", "cow", "camel", "sheep", "goat")val checkedItems = booleanArrayOf(true, false, false, true, false)builder.setMultiChoiceItems(animals, checkedItems) { dialog, which, isChecked ->    // user checked or unchecked a box}// add OK and Cancel buttonsbuilder.setPositiveButton("OK") { dialog, which ->    // user clicked OK}builder.setNegativeButton("Cancel", null)// create and show the alert dialogval dialog = builder.create()dialog.show()

Notes

  • For the context in the code above, don't use getApplicationContext() or you will get an IllegalStateException (see here for why). Instead, get a reference to the activity context, such as with this.
  • You can also populate the list items from a database or another source using setAdapter or setCursor or passing in a Cursor or ListAdapter into the setSingleChoiceItems or setMultiChoiceItems.
  • If the list is longer than will fit on the screen then the dialog will automatically scroll it. If you have a really long list, though, I'm guessing that you should probably make a custom dialog with a RecyclerView.
  • To test all of the examples above I just had a simple project with a single button than showed the dialog when clicked:

    import android.support.v7.app.AppCompatActivity;public class MainActivity extends AppCompatActivity {    Context context;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        context = this;    }    public void showAlertDialogButtonClicked(View view) {        // example code to create alert dialog lists goes here    }}

Related


You can use a custom dialog.

Custom dialog layout. list.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout    xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="wrap_content"    android:layout_height="wrap_content">    <ListView        android:id="@+id/lv"        android:layout_width="wrap_content"        android:layout_height="fill_parent"/></LinearLayout>

In your activity

Dialog dialog = new Dialog(Activity.this);       dialog.setContentView(R.layout.list)ListView lv = (ListView ) dialog.findViewById(R.id.lv);dialog.setCancelable(true);dialog.setTitle("ListView");dialog.show();

Edit:

Using alertdialog

String names[] ={"A","B","C","D"};AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);LayoutInflater inflater = getLayoutInflater();View convertView = (View) inflater.inflate(R.layout.custom, null);alertDialog.setView(convertView);alertDialog.setTitle("List");ListView lv = (ListView) convertView.findViewById(R.id.lv);ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,names);lv.setAdapter(adapter);alertDialog.show();

custom.xml

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

Snap

enter image description here