Android_自定义简便快速通用的SimpleBaseAdapter
public abstract class SimpleBaseAdapter<T> extends BaseAdapter { protected Context context; protected List<T> data; public SimpleBaseAdapter(Context context){ this(context, null); } public SimpleBaseAdapter(Context context, List<T> data) { this.context = context; this.data = data == null ? new ArrayList<T>() : new ArrayList<T>(data); } @Override public int getCount() { return data.size(); } @Override public Object getItem(int position) { if (position >= data.size()) return null; return data.get(position); } @Override public long getItemId(int position) { return position; } /** * 该方法需要子类实现,需要返回item布局的resource id * * @return */ public abstract int getItemResource(); /** * 使用该getItemView方法替换原来的getView方法,需要子类实现 * * @param position * @param convertView * @param parent * @param holder * @return */ public abstract View getItemView(int position, View convertView, ViewHolder holder); @Override public View getView(int position, View convertView, ViewGroup 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(position, convertView, holder); } public class ViewHolder { private SparseArray<View> views = new SparseArray<View>(); private View convertView; public ViewHolder(View convertView) { this.convertView = convertView; } @SuppressWarnings("unchecked") public <T extends View> T getView(int resId) { View v = views.get(resId); if (v == null) { 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 remove(int index) { data.remove(index); notifyDataSetChanged(); } public void replaceAll(List<T> elem) { data.clear(); data.addAll(elem); notifyDataSetChanged(); } }
实例代码
private class MyAdapter extends SimpleBaseAdapter<String> { public MyAdapter(Context context, List<String> data) { super(context, data); } @Override public int getItemResource() { return R.layout.layout_item; } @Override public View getItemView(int position, View convertView, SimpleBaseAdapter<String>.ViewHolder holder) { TextView tvIndex = holder.getView(R.id.item_index); TextView tvContent = holder.getView(R.id.item_content); tvIndex.setText("p:" + position); tvContent.setText(getItem(position).toString()); return convertView; } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。