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

The*_*hod 4 java enums android android-arrayadapter android-spinner

我有一个enum,它有一个映射到字符串资源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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

Spinner spinner;
spinner.setAdapter(new ArrayAdapter<MyEnum>(this, android.R.layout.simple_spinner_item, MyEnum.values()));
Run Code Online (Sandbox Code Playgroud)

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

小智 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;
    }
}
Run Code Online (Sandbox Code Playgroud)