38

For example: I have an enum with days.

How do I put its values into spinner ?

A-Sharabiani
  • 17,750
  • 17
  • 113
  • 128
saikek
  • 1,099
  • 1
  • 8
  • 15

3 Answers3

72

Similar to another answer, but you can use an ArrayAdapter to populate based on an Enum class. I would recommend overriding toString in the Enum class to make the values populated in the spinner more user friendly. In the activity:

Spinner mySpinner = (Spinner) findViewById(R.id.mySpinnerId);

mySpinner.setAdapter(new ArrayAdapter<MyEnum>(this, android.R.layout.simple_spinner_item, MyEnum.values()));

Your enum class:

public enum MyEnum{
    ENUM1("Enum 1"),
    ENUM2("Enum 2");

    private String friendlyName;

    private MyEnum(String friendlyName){
        this.friendlyName = friendlyName;
    }

    @Override public String toString(){
        return friendlyName;
    }
}
Adam
  • 1,384
  • 1
  • 16
  • 27
  • Although I prefer the other answer, it is great to learn that something like this is possible. +1 – Antiohia Jun 30 '14 at 12:14
  • If I want to change the system language, What should I do ? I cannot initialize like ENUM1("Enum 1"); – Urchin Oct 29 '14 at 18:53
  • 2
    @Urchin you could give it a stringResId then... but you have to build your own adapter to get the string from the resId instead of the toString. – SjoerdvGestel Apr 29 '15 at 10:53
  • and what if this enum is defined in library module? where is no way how to access string resource without context ? )-: – Wooff Jul 10 '15 at 07:39
44

Some kind of walkthrough is using:

Spinner mySpinner = (Spinner) findViewById(R.id.cmbClothType);
mySpinner.setAdapter(new ArrayAdapter<MyType>(this, android.R.layout.simple_list_item, MyType.values()));
dnet
  • 1,411
  • 9
  • 19
saikek
  • 1,099
  • 1
  • 8
  • 15
0

You can override the toString function in the enum class like other classes and the spinner will read the toString value.

For Ex.

enum class Duration(val value : String) {
  DURATION_HINT("Duration Unit"),
  DAY("Day"),
  WEEK("Week"),
  MONTH("Month");

  override fun toString() : String {
    return value
  }
}
Muhammad Helmi
  • 395
  • 2
  • 10