Android: Select items in a multi-select ListView i

2019-02-10 23:48发布

问题:

I am new to android development and struggling with how to select certain items in a listview hosted by an alertdialog. In the below code, lv.setItemChecked doesn't work as listview hasn't been generated yet, so I am wondering if there's any ListView or AlertDialog event which confirms that view has been generated.

String [] values = {"a","b","c"};

ArrayAdapter<String> adp = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice, values);

ListView lv = new ListView(this);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
lv.setAdapter(adp);

AlertDialog.Builder bldr = new AlertDialog.Builder(this);
bldr.setTitle("Select");
bldr.setView(lv);
bldr.setPositiveButton("Done",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handleDone();
        }
    });
bldr.setNegativeButton("Cancel",
    new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            handleCancel();
        }
    });

final Dialog dlg = bldr.create();
dlg.show();

Never mind, I got it. I was calling lv.setItemChecked(0, true) right after lv.setAdapter() call. Once I moved it after dlg.show(), it worked like a charm.

回答1:

public class DialogoSeleccion extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

 final String[] items = {"Español", "Inglés", "Francés"};

    AlertDialog.Builder builder =
            new AlertDialog.Builder(getActivity());

    builder.setTitle("Selección")
       .setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                Log.i("Dialogos", "Opción elegida: " + items[item]);
            }
        });

    return builder.create();
}
}

And you will get something like this:

If you want to remember or show the last selected item, just change the setItems method for set setSingleChoiceItems() or setMultiChiceItems(). Using setSingleChoiceItems() is easy, just pass other parameter (index for set selection, if u dont want to set, pass -1):

builder.setTitle("Selección")
  .setSingleChoiceItems(items, -1,
           new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {
            Log.i("Dialogos", "Opción elegida: " + items[item]);
        }

    });

With upper snippet you will have something like this

If you want a multichoose, you should change the method, and the second parameter now not will be a integer, should be a boolean array, by this way you will set id any option is enabled or not:

builder.setTitle("Selección")
.setMultiChoiceItems(items, null,
    new DialogInterface.OnMultiChoiceClickListener() {
    public void onClick(DialogInterface dialog, int item, boolean isChecked) {
         Log.i("Dialogos", "Opción elegida: " + items[item]);
   }
});

The result will be this:

The way to call any of the thre examples is this:

FragmentManager fragmentManager = getSupportFragmentManager();
    DialogoSeleccion dialogo = new DialogoSeleccion();
    dialogo.show(fragmentManager, "tagSeleccion");

If you know spanish this guide will help you: Complete guide for AlertDialogs or just get the complete example here, in GitHub



回答2:

This is simple copy-past solution. Replace the list variable with your ArrayList and you are good to go. Hope this helps.

final CharSequence[] dialogList = list.toArray(new CharSequence[list.size()]);
                final android.app.AlertDialog.Builder builderDialog = new android.app.AlertDialog.Builder(mContext);
                builderDialog.setTitle("Select Item");
                int count = dialogList.length;
                boolean[] is_checked = new boolean[count];

                // Creating multiple selection by using setMutliChoiceItem method
            builderDialog.setMultiChoiceItems(dialogList, is_checked,
                    new DialogInterface.OnMultiChoiceClickListener() {
                        public void onClick(DialogInterface dialog,
                                            int whichButton, boolean isChecked) {
                        }
                    });

            builderDialog.setPositiveButton("OK",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            ListView list = ((android.app.AlertDialog) dialog).getListView();
                          //ListView has boolean array like {1=true, 3=true}, that shows checked items
                        }
                    });

            builderDialog.setNegativeButton("Cancel",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ((TextView) myFilesActivity.findViewById(R.id.text)).setText("Click here to open Dialog");
                        }
                    });
            android.app.AlertDialog alert = builderDialog.create();
            alert.show();


回答3:

I found the correct Solutions:

    public void alertMultipleChoiceItems(){
    final CharSequence[] dialogList = Symbollist.toArray(new CharSequence[Symbollist.size()]);
    HashSet<String> uniqueValues = new HashSet<>(Symbollist);
    Symbollist.clear();
    for (String value : uniqueValues) {
        //... //Do something
        Symbollist.add(value);
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(AddPackageStep3.this);
    selectedItems = new ArrayList<Integer>();
    // set the dialog title
    boolean[] itemChecked = new boolean[selectedItems.size()];

    builder.setMultiChoiceItems(dialogList,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
                        selectedItems.add(which);
                    }

                    else if (selectedItems.contains(which)) {
                        // else if the item is already in the array, remove it
                        selectedItems.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 : selectedItems){
                        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();

}