I have this code to show a dialog with singlechoice(radio) options.
AlertDialog ad = new AlertDialog.Builder(this)
.setCancelable(false)
.setIcon(R.drawable.
position of the selected element is already given in the onClick method. so we can directly access the the array and get the selected item without any hassle. in this case: seq[which] will be the selected item.
I believe that you use an OnClickListener for setSingleChoiceItems()
, to listen whenever an item has been selected; then once the user hits okay, you set that item in stone. Right now you're just passing null, so nothing you can't pick up which item was selected.
1). create Array.
final ArrayList<String> arrData = new ArrayList<String>();
2). add data to array you have created.
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
arrData .add(cursor.getString(1));
// (1 = int columnIndex)
} while (cursor.moveToNext());
}
}
3). get data like this.
public void onClick(DialogInterface dialog, int item) {
Log.d("Selected", arrData.get(item) + "");
}
4). that's all :)
You can do just like this in on onClick() method
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.edit_set_waiting_period)
.setItems(R.array.str_set_waiting_period, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
L.e("selectedItmes", which + "");
ListView lw = ((AlertDialog) dialog).getListView();
Object checkedItem = lw.getAdapter().getItem(which);
L.e("checkedItem", checkedItem.toString() + "");
}
});
builder.show();
EditText et = (EditText)findViewById(R.id.editText9);
int a = Integer.valueOf(item);
et.setText(items[a]);
I tried to use ListView.setSelection(int)
but it never worked as expected so instead I decided to make use of View.setTag() to temporarily store the selected position.
.setSingleChoiceItems(adapter, -1,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ListView lv = ((AlertDialog)dialog).getListView();
lv.setTag(new Integer(which));
}
})
The tag can then be accessed easily after a button click.
.setPositiveButton(R.string.button_text,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ListView lv = ((AlertDialog)dialog).getListView();
Integer selected = (Integer)lv.getTag();
if(selected != null) {
// do something interesting
}
}
})