我正在尝试在Android中创建一个通用适配器,所以我不能一遍又一遍地写它。
问题是,它正在工作,但它不能很好地回收利用,它会显示我想要的东西,但是当我滚动时,它的顺序不一样。
public class CustomListViewAdapter<T> extends BaseAdapter {
private List<T> objects;
private LayoutInflater inflater;
private int resources;
private AdapterCommand<T> listener;
private ViewHolder h;
public CustomListViewAdapter(Context context, List<T> objects,
int resources, AdapterCommand<T> listener, ViewHolder h) {
this.h = h;
this.listener = listener;
this.resources = resources;
this.objects = objects;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return objects.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return objects.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
if (v == null) {
v = inflater.inflate(resources, parent, false);
listener.init(v, h);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
T object = (T) getItem(position);
listener.execute(object, h);
return v;
}
public interface AdapterCommand<T> {
public void init(View v, ViewHolder h);
public void execute(T object, ViewHolder h);
}
public static interface ViewHolder {
}
}
答案 0 :(得分:1)
您不能只保留一个ViewHolder实例。每次convertView为null和setTag时都需要创建新对象。
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
ViewHolder h;
if (v == null) {
v = inflater.inflate(resources, parent, false);
h = new ViewHolder();
listener.init(v, h);
v.setTag(h);
} else {
h = (ViewHolder) v.getTag();
}
T object = (T) getItem(position);
listener.execute(object, h);
return v;
}