参数说明: 构造函数的list参数是你的ListView的数据, 而viewHolder是你的ViewHolder类.
思路说明: getView方法中已经实现了view的初始化, 并且把viewholder中的字段进行注入, 然后通过view.setTag()设置给该view.
使用说明: 在抽象方法initView中通过view.getTag()拿到viewholder, 然后对里面的控件进行操作即可~
当然, 这样封装会有一些局限性, 毕竟封装了就会失去一些灵活性嘛.
public abstract class BeanAdapter extends BaseAdapter {
List mList;
Context context;
int layoutId;
Class wiewHolder;
public BeanAdapter(Context context, int layoutId, List list, Class wiewHolder) {
this.mList = list;
this.context = context;
this.layoutId = layoutId;
this.wiewHolder = wiewHolder;
}
@Override
public int getCount() {
return mList.size();
}
@Override
public Object getItem(int position) {
return mList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = LayoutInflater.from(context).inflate(layoutId, parent, false);
try {
Constructor constructor = wiewHolder.getDeclaredConstructor();
constructor.setAccessible(true);
Object obj = constructor.newInstance();
ViewUtil.setViewHolder(view, obj);
} catch (Exception e) {
}
}
initView(position, getItem(position), view, view.getTag());
return view;
}
public abstract void initView(int position, Object item, View view, Object viewHolder);
}
附上setViewHolder方法, 跟另一篇文章的属性注入findView方法类似:
//自动注入 根据viewHolder中成员变量的名称注入view,并通过setTag()设置给view
public static void setViewHolder(View view, Object viewHolder) {
try {
ViewGroup viewGroup = (ViewGroup) view;
Class clazz = viewHolder.getClass();
Field[] fields = clazz.getDeclaredFields();
String fieldName = null;
// 遍历所有字段
for (Field field : fields) {
fieldName = field.getName();
// 包含_
try {
Field idField = R.id.class.getField(fieldName);
int id = (Integer) idField.get(null);
view = viewGroup.findViewById(id);
field.setAccessible(true);
// 设置给viewHolder
field.set(viewHolder, view);
} catch (Exception e) {
}
}
// viewHolder设置给viewGroup
viewGroup.setTag(viewHolder);
} catch (Exception e) {
}
}