gpt4 book ai didi

java - 用于不止一种类类型的 ArrayAdapter

转载 作者:行者123 更新时间:2023-12-02 03:48:12 27 4
gpt4 key购买 nike

拥有可以处理多种对象类型的数组适配器的最佳实践是什么?

Adapter extends ArrayAdapter<?>

我有 3 种类型的类(class) A.class , B.class , C.class适配器中的逻辑是相同的。

public class Adapter extends ArrayAdapter<A,B,C ?> {

private int viewResourceId;
private LayoutInflater inflater;
private ArrayList<A,B,C ?> list;

public Adapter(Context context, int viewResourceId, ArrayList<A,B,C ?> list) {
super(context, viewResourceId, list);
this.viewResourceId = viewResourceId;
this.list = list;

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
return list.size();
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
Holder holder;

if (arg1 == null || arg1.getTag() == null) {
holder = new Holder();

arg1 = inflater.inflate(viewResourceId, null);
arg1.setTag(holder);

holder.textView = (TextView) arg1.findViewById(R.id.textView);
} else {
holder = (Holder) arg1.getTag();
}

// A,B,C
holder.textView.setText(list.get(arg0).getName());

return arg1;
}

static class Holder {
TextView textView;
}

}

现在我为每个类类型提供了 3 个不同的适配器,并将其设置为列表

listView.setAdapter(new Adapter(this, R.layout.row_item, list<A,B,C ?>))

最佳答案

你可以让它通用 -

    public class Adapter<T> extends ArrayAdapter<T> {

private int viewResourceId;
private LayoutInflater inflater;
private ArrayList<T> list;

public Adapter(Context context, int viewResourceId, ArrayList<T> list) {
super(context, viewResourceId, list);
this.viewResourceId = viewResourceId;
this.list = list;

inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
return list.size();
}

@Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
Holder holder;

if (arg1 == null || arg1.getTag() == null) {
holder = new Holder();

arg1 = inflater.inflate(viewResourceId, null);
arg1.setTag(holder);

holder.textView = (TextView) arg1.findViewById(R.id.txtUse);
} else {
holder = (Holder) arg1.getTag();
}

// A,B,C
if(list.get(arg0) instanceof A){
//User A's property to set TextView text
} else if(list.get(arg0) instanceof B){
//User B's property to set TextView text
} else if(list.get(arg0) instanceof C){
//User C's property to set TextView text
}

return arg1;
}

static class Holder {
TextView textView;
}
}

关于java - 用于不止一种类类型的 ArrayAdapter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36139024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com