获得一个枚举值了一个Android微调的 [英] Getting an enumerated value out of an Android Spinner
本文介绍了获得一个枚举值了一个Android微调的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经写了下面的类来让我得到一个枚举值了一个Android微调的。
有两行的getValue()
既不是其中的编译。
我应该怎么做呢?
公共类EnumSpinnerListener<吨扩展Enum>实现AdapterView.OnItemSelectedListener {
私人字符串mValue = NULL; 公共EnumSpinnerListener(适配器视图<>适配器视图){
adapterView.setOnItemSelectedListener(本);
} @覆盖
公共无效onItemSelected(适配器视图<>适配器视图,视图观点,INT I,长L){
mValue = adapterView.getItemAtPosition(ⅰ)的ToString();
} @覆盖
公共无效onNothingSelected(适配器视图<>适配器视图){
// 没做什么
} 公共ŧ的getValue(){
返回Enum.valueOf(T.class,mValue); //不能从类型变量选择
返回T.valueOf(mValue); //的valueOf;枚举(java.lang.Class中&LT T&GT ;,字符串)不能用于(java.lang.String中)
}
}
解决方案
由于<一个href=\"http://stackoverflow.com/questions/339699/java-generics-type-erasure-when-and-what-happens\">type擦除, T
将在运行时没有任何意义,这就是为什么前pression T.class
是非法的。解决方法是引用类&LT; T&GT;
实例:
公共类EnumSpinnerListener&LT;吨扩展Enum&LT; T&GT;&GT; //注意这里的修正
实现AdapterView.OnItemSelectedListener { 私人最终级&LT; T&GT;类型; 私人字符串mValue = NULL; 公共EnumSpinnerListener(类&LT; T&GT;类型,适配器视图&LT;&GT;适配器视图){
this.type =类型;
adapterView.setOnItemSelectedListener(本);
} 公共ŧ的getValue(){
返回Enum.valueOf(类型,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微调的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文