listview优化,convertview重复使用,并使用viewholder

listview中的优化,不仅包含convertview的重用,而且要使用viewholder让convertview中的各个组件也都可以重用,如果每次使用findViewById,效率会降低很多。下面是代码:

如果在getView中存在按钮的点击事件,也应该再getview之外定义好,然后再getView中重用,而不是在getView中每次new一个。

public View getView(int postion, View convertView, ViewGroup parent) {
 ViewHolder holder = null;
 if(convertView == null){
 convertView = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.kedan_yixiadan_listitem, null);
 holder = new ViewHolder();
 holder.caiming = (TextView)convertView.findViewById(R.id.caiming);
 holder.jiage = (TextView)convertView.findViewById(R.id.jiage);
 holder.shuliang = (TextView)convertView.findViewById(R.id.yidian_cai_shuliang);
 holder.beizhuBtn = (Button)convertView.findViewById(R.id.beizhu_item_btn);
 holder.zhangdanPinpan = (LinearLayout)convertView.findViewById(R.id.zhangdan_pinpan);
 holder.zhangdanTaocan = (LinearLayout)convertView.findViewById(R.id.zhangdan_taocan);
 holder.zhangdanZengcai = (LinearLayout)convertView.findViewById(R.id.zhangdan_zengcai);
 convertView.setTag(holder);
 }else{
 holder = (ViewHolder)convertView.getTag();
 }
 
 YidianCais cai = (YidianCais)yixiadanList.get(postion);
 holder.caiming.setText(cai.getCnName());
 holder.shuliang.setText(cai.getNum() + " 份");
 holder.jiage.setText(cai.getPrice() + " 元/" + cai.getUnit());
 
 holder.beizhuBtn.setTag(cai.getCnName());
 holder.beizhuBtn.setTag(R.id.tag_id, cai.getId());
 holder.beizhuBtn.setTag(R.id.tag_name, cai.getCnName());  return convertView;
 }
private class ViewHolder{
    	private TextView caiming;
    	private TextView jiage;
    	private TextView shuliang;
    	private Button beizhuBtn;
    	private TextView jiageUnit;
    	private LinearLayout zhangdanPinpan;
    	private LinearLayout zhangdanTaocan;
    	private LinearLayout zhangdanZengcai;
    	private Button zhangdanJianBtn;
    	private Button zhangdanJiaBtn;
    }







你可能感兴趣的:(listview优化,convertview重复使用,并使用viewholder)