Android - Java通用SpinnerAdapter

时间:2010-11-06 19:28:10

标签: android generics spinner

我正在寻找一种方法:

public class SimpleText_SpinnerAdapter extends ArrayAdapter<Enum1> {
   many lines of code with a one moment : String val = oneEnum1val_inparam.getlabel();
}

public class SimpleText_SpinnerAdapter extends ArrayAdapter<Enum2> {
   exactly the same code than previously, but for Enum2
}

public class SimpleText_SpinnerAdapter extends ArrayAdapter<Enum3> {
   exactly the same code than previously, but for Enum3
}

这是为3个微调器提供了3个适配器,它包含来自3个不同的枚举值,枚举构造方式完全相同但值不同。

当然,每个枚举类型都有一个getLabel()方法。

我想找到一种方法来做到这一点,而无需为每个适配器复制粘贴3次相同的代码。一种通用的,可由3个专用的引用。

我找不到解决方案。 你能帮帮我吗?

或者如果你有更高效的东西......

奥利弗

1 个答案:

答案 0 :(得分:4)

怎么样:

public class SimpleText_SpinnerAdapter<T extends Enum<T> & ProvidesLabel>
    extends ArrayAdapter<T>
{
    // implementation
}



public enum Enum1 implements ProvidesLabel
{
        Entry1("label 1"),
        Entry2("label 2");

    private final String label;

    private Enum1(String label)
    {
        this.label = label;
    }

    @Override 
    public String getLabel()
    {
        return this.label;
    }
}

public interface ProvidesLabel
{
    String getLabel();
}

使用(nm构造函数)实例化类:

 SimpleText_SpinnerAdapter<Enum1> enum1 =
        new SimpleText_SpinnerAdapter<Enum1>(context, textViewResourceId);