万能ListView Adapter

//抽象封装ViewHolder

public class MyViewHolder {
private SparseArray<View> mViews;
private View mconvertView;


public MyViewHolder(Context context, int layoutId) {
super();
mViews = new SparseArray<View>();
this.mconvertView = View.inflate(context, layoutId, null);
mconvertView.setTag(this);
}


public static MyViewHolder getHolder(Context context, View convertView,
int layoutId) {
if (convertView == null) {
return new MyViewHolder(context, layoutId);
} else {
return (MyViewHolder) convertView.getTag();
}


}


public View getView(int ViewID) {
View view = mViews.get(ViewID);
if (view == null) {
view = mconvertView.findViewById(ViewID);
mViews.put(ViewID, view);
}


return view;
}


public View getConvertView() {
return mconvertView;
}


}


//adapter

public abstract class MyAdapter<T> extends BaseAdapter {
private Context context;
private ArrayList<T> data;
private int layoutId;


public MyAdapter(Context context, ArrayList<T> data, int layoutId) {
super();
this.context = context;
this.data = data;
this.layoutId = layoutId;
}


@Override
public int getCount() {
// TODO Auto-generated method stub
return data.size();
}


@Override
public T getItem(int arg0) {
// TODO Auto-generated method stub
return data.get(arg0);
}


@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}


@Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder holder = MyViewHolder.getHolder(context, convertView,
layoutId);
convert(holder, getItem(position));
return holder.getConvertView();


}


public abstract void convert(MyViewHolder holder, T bean);
}


//使用方法



list_view = (ListView) findViewById(R.id.list_view);
list_view.setAdapter(new MyAdapter<Bean>(MainActivity.this, data,
R.layout.item) {


@Override
public void convert(MyViewHolder holder, Bean bean) {
TextView title = (TextView) holder.getView(R.id.title);
title.setText(bean.getTitle());
TextView desc = (TextView) holder.getView(R.id.desc);
desc.setText(bean.getDesc());
TextView time = (TextView) holder.getView(R.id.time);
time.setText(bean.getTime());
TextView phone = (TextView) holder.getView(R.id.phone);
phone.setText(bean.getPhone());
}
});



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值