Reputation: 1717
I have a simple AlertDialog with a setSingleChoiceItems list of two elements which works fine.
final CharSequence[] blackwhite = {"White", "Black"};
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Title");
alertDialogBuilder
.setCancelable(false)
.setSingleChoiceItems(blackwhite, -1,null)
.setPositiveButton("Start", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ListView lw = ((AlertDialog) dialog).getListView();
Object checkedItem = lw.getAdapter().getItem(lw.getCheckedItemPosition());
// Do something with checkedItem
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
In the rest of the code, these two items actually correspond to an enum:
public enum Player {
WHITE, BLACK
}
Is there an elegant way of using the enum directly in setSingleChoiceItems without manually converting to String/CharSequence? For instance if I later decide to change "WHITE" to "GREEN" in the enum only, this should automatically show up in the alert dialog as well.
Upvotes: 5
Views: 2364
Reputation: 1321
You can obtain the String value of a Player
using the toString()
method.
Player.WHITE.toString(); // returns "WHITE"
You could do something like:
public enum Player {
WHITE, BLACK, GREEN, PURPLE
public static String[] getValues() {
String[] strs = new String[Player.values().length];
int i = 0;
for (Player p: all)
strs[i++] = p.toString().toLowerCase();
return strs; // ["white", "black", "green", "purple"]
}
}
I hope it helps!
Upvotes: 7