只上代码不多说话
public abstract class ABaseAdapter extends BaseAdapter{ Context context; protected ABaseAdapter(Context context) { this.context = context; } protected ABaseAdapter() { } /** * 各个控件的缓存 */ public class ViewHolder{ public SparseArrayviews = new SparseArray (); /** * 指定resId和类型即可获取到相应的view * @param convertView * @param resId * @param * @return */ public T obtainView(View convertView, int resId){ View v = views.get(resId); if(null == v){ v = convertView.findViewById(resId); views.put(resId, v); } return (T)v; } } /** * 改方法需要子类实现,需要返回item布局的resource id * @return */ public abstract int itemLayoutRes(); @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder; if(null == convertView){ holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(itemLayoutRes(), null); convertView.setTag(holder); }else{ holder = (ViewHolder) convertView.getTag(); } return getView(position, convertView, parent, holder); } /** * 使用该getView方法替换原来的getView方法,需要子类实现 * @param position * @param convertView * @param parent * @param holder * @return */ public abstract View getView(int position, View convertView, ViewGroup parent, ViewHolder holder); }
ABaseAdapter的用法:
1:编写适配类直接继承该ABaseAdapter。
2.在构造方法中调用父类的方法:
即:
public MyAdapter(Context context){ super(context); }
3:重写父类方法itemLayoutRes():
@Overridepublic int itemLayoutRes() {return R.layout.caipu_griditem;//返回布局的文件}
4:重写父类额抽象方法getView(),绑定数据:
@Override public View getView(int position, View convertView, ViewGroup parent, ViewHolder holder) { ImageView imageView = holder.obtainView(convertView, R.id.cp_grid_img); TextView textView = holder.obtainView(convertView, R.id.cp_grid_text); imageView.setBackgroundResource(IMAGES[position]); textView.setText(TITLES[position]); return convertView; }
结果简洁了许多。好东西,记得要分享!