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