文章目录
完成了基本的ViewHolder和List数据管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
| public abstract class SimpleBaseAdapter<T> extendsBaseAdapter { protected Context context; protected List<T> data;
public SimpleBaseAdapter(Context context,List<T> data) { this.context = context; this.data = data == null ? new Array<T>() : new ArrayList<T>(data); }
@Override public int getCount() { return data.size(); }
@Override public Object getItem(int postion) { if (postion >= data.size) { return null; } return data.get(postion); }
@Override public long getItemId(int postion) { return postion; }
public abstract int getItemResoure();
public abstract View getItemView(int postion,View convertView,ViewHolder holder);
@Override public View getView(int postion,View convertView,ViewGoup parent) { ViewHolder holder; if (null == convertView) { convertView = View.inflate(context,getItemResource(),null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } return getItemView(postion,convertView,holder); }
public class ViewHolder { private SparseArray<View> views = new SparseArray<View>(); private View convertView;
public ViewHolder(View convertView) { this.convertView = convertView; }
public <T extends View> T getView(int resId) { View v = views.get(resId); if (null == v) { v = convertView.findViewById(resId); views.put(resId,v); } return (T) v; } }
public void addAll(List<T> elem) { data.addAll(elem); notifyDataSetChanged(); }
public void remove(T elem) { data.remove(elem); notifyDataSetChanged(); }
public void remoce(int index) { data.remove(index); notifyDataSetChanged(); }
public vodi replaceAll(List<T> elem) { data.clear(); data.allAll(elem); notifyDataSetChanged(); } }
|
在实现时主要关注getItemResource
和getItemView
方法
- getItemResource返回layout资源ID
- getItemView中利用数据加载Item View