拥有可以处理多种对象类型的数组适配器的最佳做法是什么?
Adapter extends ArrayAdapter<?>
我有3种类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 ?>))
答案 0 :(得分:2)
你可以把它变成通用的 -
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;
}
}