为了更方便高效的使用BaseAdapter,特意抽取了一下,下面是简单的结构图:
需要4个类:
【MyBaseAdapter3】:
public abstract class MyBaseAdapter3<T> extends BaseAdapter {
public List<T> list;
public MyBaseAdapter3(List<T> list) {
this.list = list;
}
@Override
public int getCount() {
return list==null?0:list.size();
}
@Override
public Object 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) {
T t=list.get(position);
BaseHolder holder;
if(convertView==null){
holder=getHolder();
}else{
holder= (BaseHolder) convertView.getTag();
}
//绑定数据
holder.setData(t);
return holder.getRootView();
}
public abstract BaseHolder getHolder();
}
【MyAdapter3】:
public class MyAdapter3 extends MyBaseAdapter3<Product>{
public MyAdapter3(List<Product> list) {
super(list);
}
@Override
public BaseHolder getHolder() {
return new MyHolder();
}
}
【BaseHolder】:
public abstract class BaseHolder<T> {
private View rootView;//每个item
private T t;//每个item的数据
public BaseHolder() {
rootView=initView();
rootView.setTag(this);
ButterKnife.bind(this,rootView);
}
public void setData(T t){
this.t=t;
refreshData(t);
}
public View getRootView() {
return rootView;
}
public abstract View initView();
protected abstract void refreshData(T t);
}
【MyHolder】:
public class MyHolder extends BaseHolder<Product> {
@Bind(R.id.p_name)
TextView pName;
@Bind(R.id.p_money)
TextView pMoney;
@Bind(R.id.p_yearlv)
TextView pYearlv;
@Bind(R.id.p_suodingdays)
TextView pSuodingdays;
@Bind(R.id.p_minzouzi)
TextView pMinzouzi;
@Bind(R.id.p_minnum)
TextView pMinnum;
@Bind(R.id.p_progresss)
RoundProgress2 pProgresss;
@Override
public View initView() {
return UIUtils.getXmlView(R.layout.item_product_list);
//一般将MyHolder写在MyAdapter3里变成内部类,这样上下文就可以使用Activity了
}
@Override
protected void refreshData(Product product) {
pMinnum.setText(product.getMemberNum());
pMinzouzi.setText(product.getMinTouMoney());
pMoney.setText(product.getMoney());
pName.setText(product.getName());
pSuodingdays.setText(product.getSuodingDays());
pYearlv.setText(product.getYearLv());
pProgresss.setProgress(Integer.parseInt(product.getProgress()));
}
}
【说明1】:一般将MyHolder写成适配器的内部类,这样上下文就可以使用Activity,使用Application作为上下文还有有些样式问题的隐患。
【说明2】:MyHolder用到了工具类UIUtils的下面一个方法,MyApplication extends Application
public static View getXmlView(int layoutId){
return View.inflate(MyApplication.mContext, layoutId, null);
}