从Android Spinner中获取枚举值

时间:2013-07-22 09:30:38

标签: java android generics enums spinner

我写了下面的课程,让我从Android Spinner中获取一个枚举值。

getValue()中有两行都没有编译。

我该怎么做?

public class EnumSpinnerListener<T extends Enum> implements AdapterView.OnItemSelectedListener {
    private String mValue = null;

    public EnumSpinnerListener(AdapterView<?> adapterView) {
        adapterView.setOnItemSelectedListener(this);
    }

    @Override
    public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
        mValue = adapterView.getItemAtPosition(i).toString();
    }

    @Override
    public void onNothingSelected(AdapterView<?> adapterView) {
        // do nothing
    }

    public T getValue() {
        return Enum.valueOf(T.class, mValue); // cannot select from a type variable
        return T.valueOf(mValue); // valueOf(java.lang.Class<T>, String) in enum cannot be applied to (java.lang.String)
    }
}

1 个答案:

答案 0 :(得分:1)

由于type erasureT在运行时没有意义,这就是表达式T.class是非法的原因。解决方法是引用Class<T>实例:

public class EnumSpinnerListener<T extends Enum<T>> // note the correction here
implements AdapterView.OnItemSelectedListener {

    private final Class<T> type;

    private String mValue = null;

    public EnumSpinnerListener(Class<T> type, AdapterView<?> adapterView) {
        this.type = type;
        adapterView.setOnItemSelectedListener(this);
    }

    public T getValue() {
        return Enum.valueOf(type, mValue);
    }
}