Ah Yong Ah Yong - 8 months ago 37
Android Question

Retrieve Enum's label to form a List

I have a Enum class called CustomEnum

public enum CustomEnum
{
A("lbl1"),
B("lbl2"),
C("lbl3"),
D("lbl4");

private final String label;

CustomEnum(String label)
{
this.label = label;
}

public String getLabel()
{
return label;
}
}


I want to create a list that contain the label of the Enum, after that I set the list into
ArrayAdapter
for
Spinner
, this is how I do it:


List<CustomEnum> myList = Arrays.asList(CustomEnum.values());
ArrayAdapter adapterStation = new ArrayAdapter(getActivity(), android.R.layout.simple_spinner_dropdown_item, myList);


From the
Spinner
the list is
"A" "B" "C" "D"
instead of
"lbl1" "lbl2" "lbl3" "lbl4"
, how to do that?

Answer Source

You have to retrieve the labels and store them in the list.

List<String> myList = Arrays.stream(CustomEnum
.values())
.map(e -> e.getLabel())
.collect(Collectors.toList());

EDIT: The ideal way would be to override toString() to return the label.