主要代碼轉至:http://www.stormzhang.com/androidtips/2014/08/31/android-common-simplebaseadapter/
java
部分代碼有作修改。android
public abstract class ABaseAdapter<T> extends BaseAdapter { protected List<T> list; protected Context context; protected LayoutInflater inflater; public ABaseAdapter(Context context, List<T> list) { this.list = list; inflater = LayoutInflater.from(context); this.list = list == null ? new ArrayList<T>() : list; this.context = context; } @Override public int getCount() { return list.size(); } @Override public T getItem(int position) { return list.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if (convertView == null) { convertView = inflater.inflate(getItemResource(), null); holder = new ViewHolder(convertView); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } return getItemView(position, convertView, holder); } public class ViewHolder { SparseArray<View> viewArray = new SparseArray<View>(); View convertView; public ViewHolder(View convertView) { this.convertView = convertView; } public <T extends View> T getView(int resId) { View v = viewArray.get(resId); if (v == null) { v = convertView.findViewById(resId); viewArray.append(resId, v); } return (T) v; } } /** * 須要返回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); }
實現類app
public class ShopAdapter extends ABaseAdapter<Shop> { public ShopAdapter(Context context, List<Shop> list) { super(context, list); } @Override public int getItemResource() { return R.layout.item_shop; } @Override public View getItemView(int position, View convertView, ViewHolder holder) { TextView tvName = holder.getView(R.id.tvName); tvName.setText("姓名"); return convertView; } }