使用具有字符串资源的Enum填充Spinner

时间:2014-08-18 17:47:01

标签: java android enums android-arrayadapter android-spinner

我有一个枚举,它有一个映射到字符串资源ID的属性,如下所示:

public enum MyEnum{

  FIRST(1,R.string.first_enum_desc),
  SECOND(2,R.string.second_enum_desc);

  private int mId;
  private int mDescriptionResourceId;

  private MyEnum(id,descriptionResourceId) {
      mId = id;
      mDescriptionResourceId = descriptionResourceId;
  }

  public toString(context){
      return context.getString(mDescriptionResourceId);
  }
}

我想用enum填充一个微调器,问题只是使用我的类型的适配器:

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

我没有得到字符串资源描述,因为适配器隐式调用toString(),它返回枚举名称。我不知道该怎么办。无论我需要Context来获取字符串值。有人可以建议实现我想要的最佳方式吗?我只需要一个正确的方向。任何意见,将不胜感激。非常感谢!

2 个答案:

答案 0 :(得分:9)

您应该构建自己的ArrayAdapter。然后重写方法getView()和getDropDownView。

public class MyAdapter extends ArrayAdapter<MyEnum> {

    public MyAdapter (Context context) {
        super(context, 0, MyEnum.values());
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
         CheckedTextView text= (CheckedTextView) convertView;

         if (text== null) {
             text = (CheckedTextView) LayoutInflater.from(getContext()).inflate(android.R.layout.simple_spinner_dropdown_item,  parent, false);
         }

         text.setText(getItem(position).getDescriptionResourceId());

         return text;
    }

    @Override
    public View getDropDownView(int position, View convertView, ViewGroup parent) {
        CheckedTextView text = (CheckedTextView) convertView;

        if (text == null) {
            text = (CheckedTextView) LayoutInflater.from(getContext()).inflate(android.R.layout.simple_spinner_dropdown_item,  parent, false);
        }

        text.setText(getItem(position).getTitle());

        return text;
    }
}

答案 1 :(得分:2)

检索枚举的最简单方法是提供其视图位置,或者其项目位置正在获取其位置:当您传递枚举值时,它们将按照它们声明的顺序显示。例如,在OnItemClickListener

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    MyEnum value = MyEnum.values()[position];
    ...
}

另一个解决方案是检索视图的文本,然后使用Enum.valueOf解析枚举,但这需要知道显示项目的TextView的id,并且与第一个解决方案相比似乎很复杂。类似的东西:

public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    String text = ((TextView) parent.findViewById(R.id.mytextview)).getText();
    MyEnum value = MyEnum.valueOf(text);
}

最后,您还可以从适配器中检索枚举并进行转换,例如:

MyEnum.class.cast(myListView.getAdapter().getItem(position))