Android: Seleccionar elementos en un ListView multi-select dentro de AlertDialog

Soy nuevo en el desarrollo de Android y luchando con la forma de seleccionar ciertos elementos en un listview alojado por un alertdialog. En el siguiente código, lv.setItemChecked no funciona como listview no se ha generado todavía, así que me pregunto si hay algún evento ListView o AlertDialog que confirme que se ha generado la vista.

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(); 

No importa, lo tengo. Estaba llamando a lv.setItemChecked (0, true) justo después de lv.setAdapter () llamar. Una vez que lo trasladé después de dlg.show (), funcionó como un encanto.

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

Y obtendrá algo como esto:

introduzca la descripción de la imagen aquí

Si desea recordar o mostrar el último elemento seleccionado, cambie el método setItems para set setSingleChoiceItems () o setMultiChiceItems (). El uso de setSingleChoiceItems () es fácil, sólo pasar otro parámetro (índice para la selección del conjunto, si u no quiere establecer, pasar -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]); } }); 

Con el fragmento superior tendrás algo como esto

introduzca la descripción de la imagen aquí

Si desea un multichoose, debe cambiar el método, y el segundo parámetro ahora no será un entero, debe ser una matriz booleana, de esta manera se establecerá id cualquier opción está habilitada o no:

 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]); } }); 

El resultado será el siguiente:

introduzca la descripción de la imagen aquí

La forma de llamar a cualquiera de los tres ejemplos es la siguiente:

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

Si sabes español, esta guía te ayudará a: Completar la guía de AlertDialogs o simplemente obtener el ejemplo completo aquí, en GitHub

Esta es una simple copia-pasado solución. Reemplazar la variable de list con su ArrayList y usted está bien para ir. Espero que esto ayude.

 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(); 

He encontrado las soluciones correctas:

  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(); } 
  • Android: Creación de una vista de lista dinámica
  • Centrar verticalmente un texto en una fila de vista de lista
  • ¿Cómo puedo cambiar el color de fondo de una fila específica correctamente en un ListView? (Androide)
  • Android, vacío listview afrer atrás de otro fragmento
  • ListView Item Selected Estado no funciona
  • Android ListView desplazamiento rápido con secciones: texto de sección demasiado largo
  • Android Descargar varios archivos y mostrar el progreso en ListView
  • Cómo detectar si un listview está desplazándose hacia arriba o hacia abajo en android?
  • Android: ¿debería un adaptador listView ser parte de tu clase ViewModel?
  • Obtener el ID del elemento ListView seleccionado (datos rellenos con DB de SQLite)
  • ¿Cuál usar WebView o TextView en una lista con datos HTML en ella?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.