问题
I'm trying to create a generic adapter in Android, so i can not write it over and over.
The thing is,it's working, but it's not recycling very well, it displays what i want but when i scroll, it's not in the same order.
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 {
}
}
回答1:
You cannot keep only one instance of ViewHolder. You need to create new object everytime the convertView is null and 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;
}
来源:https://stackoverflow.com/questions/24994661/custom-android-adapter-with-generic-class