Custom android adapter with generic class

帅比萌擦擦* 提交于 2019-12-10 11:07:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!