我有一个通用适配器用于所有类型的listView但我在ListView中获得了重复的项目。当我来回滚动时,有时会更改项目顺序。有一些线程,但没有通用适配器。我知道Android重用了Ui对象,但getView中的视图总是为null(表示android Studio)
以下是我的适配器代码:
界面:
#edit
}
BaseView类:
public interface Adaptable {
public View buildView(View v, LayoutInflater inflater, ViewGroup parent);
自定义适配器类:
public abstract class BaseView<T,E> implements Adaptable{
private static final String TAG = "BaseView";
protected int layoutId;
protected T viewHolder;
protected E entity;
public BaseView(){
}
public BaseView(E entity, int layoutId){
this.entity = entity;
this.layoutId = layoutId;
}
protected void invokeView(View v){
try {
Field fs[] = viewHolder.getClass().getFields();
for (Field f : fs) {
InvokeView a = f.getAnnotation(InvokeView.class);
int id = a.viewId();
Log.d(TAG, "field name: " + f.getName());
Log.d(TAG, "view id: " + id);
Log.d(TAG, "class: " + f.getClass());
f.set(viewHolder, v.findViewById(id));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
@SuppressWarnings("unchecked")
@Override
public View buildView(View v, LayoutInflater inflater, ViewGroup parent) {
// load the view
if (null == v) {
v = inflater.inflate(layoutId, parent, false);
// get the view
invokeView(v);
v.setTag(viewHolder);
} else {
viewHolder = (T) v.getTag();
}
// binding logic data to view
mappingData(viewHolder, entity, v.getContext());
return v;
}
protected abstract void mappingData(T viewHolder, E entity, Context mContext);
}
InvokeView界面:
public class CustomListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private List<Adaptable> items;
@SuppressWarnings("unchecked")
public CustomListAdapter(List<?> items, Context c) {
this.items = (List<Adaptable>) items;
inflater = LayoutInflater.from(c);
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return items.get(position).buildView(convertView, inflater, parent); }
}
这是我在我的活动中设置的方式:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface InvokeView {
int viewId();
}
如果有人有想法。
提前感谢您的帮助。