Reputation: 63
Suppose I want to create a simple dialog using AlertDialog.Builder. Is there any nice way to get rid of written "by hand" comparison to integers in it's OnClickListener?
I can make some constants, but it still is something that has to be changed in 2 places, if somebody adds another item to menu.
final CharSequence[] menuOptions = new CharSequence[]{"one","two","three"};
AlertDialog.Builder builder = new AlertDialog.Builder(MapBrowsingActivity.this);
builder.setTitle("Choose action").
setItems(menuOptions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
//do sth;
}
if (which == 1) {
//do sth;
}
if (which == 2) {
//do sth;
}
}
});
builder.create().show();
Upvotes: 0
Views: 287
Reputation: 39863
You cannot really do anything about it. If somebody changes the menu items, also the handling should be changed. You could use a switch
to make it a little clearer though:
switch(what) {
case 0:
//do sth;
break;
case 1:
//do sth;
break;
case 2:
//do sth;
break;
default:
throw new RuntimeException("item unknown");
}
Upvotes: 1
Reputation: 5020
You can use next approach which is based on usage of enum
. It requires additional stuff with converting enum
to CharSequence
, but guarantees that when you or another developer will add/remove/insert new menu app would work ok.
private void showMenu() {
final Menu[] values = Menu.values();
CharSequence[] items = new CharSequence[values.length];
for (int i = 0; i < values.length; i++) {
items[i] = values[i].toString();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose action").
setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Menu value = values[which];
switch (value) {
case Menu1:
break;
case Menu2:
break;
case Menu3:
break;
}
}
});
builder.create().show();
}
private enum Menu {
Menu1,
Menu2,
Menu3
}
Upvotes: 3