Android: Select items in a multi-select ListView inside AlertDialog

后端 未结 3 1204
-上瘾入骨i
-上瘾入骨i 2021-01-01 04:50

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

3条回答
  •  粉色の甜心
    2021-01-01 04:59

    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:

    enter image description here

    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

    enter image description here

    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:

    enter image description here

    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

提交回复
热议问题