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.
This is simple copy-past solution. Replace the
list
variable with your ArrayList and you are good to go. Hope this helps.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):
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:
The result will be this:
The way to call any of the thre examples is this:
If you know spanish this guide will help you: Complete guide for AlertDialogs or just get the complete example here, in GitHub
I found the correct Solutions: