• 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;
     }

  • 相关阅读:
    常用git命令及问题解决方法
    angular router-ui
    lodash接触:string-capitalize
    angular-ui-router状态不变刷新页面
    ubuntu安装bower失败的解决方法
    HTTP协议中PUT和POST使用区别 【转载】
    CentOS6.5配置python开发环境之一:CentOS图形化界面显示
    SQL Server 查询Job中的存储过程(转)
    sql 取每月第一天或最后一天
    getdate() 转换格式大全
  • 原文地址:https://www.cnblogs.com/hgb1116/p/5919203.html
Copyright © 2020-2023  润新知