Getting an enumerated value out of an Android Spinner

纵饮孤独 提交于 2019-12-07 23:58:12

问题


I've written the class below to let me get an enumerated value out of an Android Spinner.

There are two lines in getValue() neither of which compile.

How should I do this?

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:


Due to type erasure, T will have no meaning at runtime, which is why the expression T.class is illegal. The workaround is to reference a Class<T> instance:

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);
    }
}


来源:https://stackoverflow.com/questions/17784067/getting-an-enumerated-value-out-of-an-android-spinner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!