Spinner获取枚举值

Spinner获取枚举值

本文介绍了从Android Spinner获取枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面写了一个类,让我从Android Spinner中获得一个枚举值。



getValue中有两行()这两个都不编译。



我该怎么做?

  public class EnumSpinnerListener< T extends Enum>实现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 ⅰ)的ToString();
}

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

public T getValue(){
return Enum.valueOf(T.class,mValue); //不能从类型变量中选择
返回T.valueOf(mValue);枚举中的valueOf(java.lang.Class< T>,String)不能应用于(java.lang.String)
}
}
/ pre>

解决方案

由于, T 在运行时没有意义,这就是为什么表达式 T.class 是非法的。解决方法是引用类< T> 实例:

  public类EnumSpinnerListener< T扩展枚举< T>> //注意这里的修正
实现了AdapterView.OnItemSelectedListener {

private final Class< T>类型;

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


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)
    }
}
解决方案

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

这篇关于从Android Spinner获取枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:02