ListView in AlertDialog
suggest changeWe can always use ListView or RecyclerView to select from a list of items, but if we have a small number of choices and we want the user to select one of them, we can use AlertDialog.Builder.setAdapter.
private void showDialog()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose any item");
final List<String> labels = new ArrayList<>();
labels.add("Item 1");
labels.add("Item 2");
labels.add("Item 3");
labels.add("Item 4");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, labels);
builder.setAdapter(dataAdapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this,"You have selected " + labels.get(which),Toast.LENGTH_LONG).show();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
If we do not need a particular ListView, the basic approach is setItems. TAG is not declared on this page:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select an item")
.setItems(R.array.your_array, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position of the selected item
Log.v(TAG, "Selected item on position " + which);
}
});
builder.create().show();
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents