I'm looking to use enums for a list inside of a spinner widget on android. I have my enums setup as follows:
public enum States{
AL("Alabama"),
AK("Alaska"),
AR("Arkansas"),
AZ("Arizona"),
CA("California"),
CO("Colorado"),
... (etc.)
}
My current array adapter is setup as follows:
mAddressState.setAdapter(new ArrayAdapter<States>(this, android.R.layout.simple_list_item_1, States.values()));
This almost works, but in my spinner list I end up with the abbreviations, rather than the state names (which is what I'm going for). Is there a workaround to get this setup correctly?
I hope that this helps someone. It took me a while to figure it out for myself. The trick is to override toString in your enum. The code for your states enum would be:
public enum States{
AL("Alabama"),
AK("Alaska"),
AR("Arkansas"),
AZ("Arizona"),
CA("California"),
CO("Colorado"),
... (etc.);
private String theState;
States(String aState) {
theState = aState;
}
@Override public String toString() {
return theState;
}
}
Then, create the adapter just as you do:
mAddressState.setAdapter(new ArrayAdapter<States>(this,
android.R.layout.simple_list_item_1, States.values()));
and the long names will show up in the spinner. To get the abbreviated name from the adapter, to store the selected one for instance, use the enum.name() function. For instance:
Spinner spinner = (Spinner) myView.findViewById(R.id.theState);
String selected = ((States)spinner.getSelectedItem()).name();