listview 的优化

对于ListView的优化,主要是在表现在getView 这个方法中,这个方法是最重要的,也是最复杂的,getView()有三个参数,position表示将显示的是第几行(也就是第几个条目),covertView是从布局文件中inflate来的布局。

下面这段代码做了三个方面的优化,都是在getView方法里面,大家仔细看看。

首先是重用了convertView,这是因为ListView的自身的一个缓存机制,它会缓存条目中的一个条目item,当listview第一屏显示完成之后,就会出现一个缓存条目。大家想一想,如果不重用convertView,每次显示一个新的条目的时候,都会执行inflater方法,也就是说每次都要去解析我们的list_item布局文件,这是一个非常耗时的操作,一旦数据过多了,很容易内存溢出,并且会越来越卡,可以想象,这样写出来的APP是不堪入目的,估计也没几个人会用额。

第二个是减少findViewById的次数,findViewById是一个相对比较耗性能的操作,因为这个操作每次都需要到布局中去查找文件。把item里面的控件封装成一个javaBean,当item条目被加载的时候就去找到对应的控件。

 

public View getView(int position, View convertView, ViewGroup parent) {
  ViewHolder holder;
     if (convertView == null) {
             convertView = LayoutInflater.from(context).inflate(R.layout.item_lv, null);
             holder = new ViewHolder();
             holder.iv=(ImageView) convertView.findViewById(R.id.item_iv);
    holder.tvName=(TextView) convertView.findViewById(R.id.item_name);
    holder.tvprice=(TextView) convertView.findViewById(R.id.item_price);
    holder.tvCountOfMounth=(TextView) convertView.findViewById(R.id.item_countOfMounth);
             convertView.setTag(holder);
     }
     else{
             holder = (ViewHolder)convertView.getTag();
     }
   
     FoodBeans fb=fbs.get(position);
     holder.iv.setImageResource(fb.getIcon());
     holder.tvName.setText(fb.getName());
     holder.tvprice.setText("¥"+fb.getPrice()+"/份");
     holder.tvCountOfMounth.setText("月售"+fb.getCountOfMounth());
     Log.i("myTag", "position:"+position);
  Log.i("myTag", "convertView:" + convertView);
     return convertView;
 }
 static class ViewHolder {
      TextView tvprice;
         TextView tvName;
         ImageView iv;
         TextView tvCountOfMounth;
 }

posted @ 2016-09-29 11:13  相忘江湖_侯  阅读(152)  评论(0编辑  收藏  举报