当前位置:操作系统 > 安卓/Android >>

Android ApiDemos示例解析(181):Views->Lists->14.Efficient Adapter

上例使用临时数据来绑定列表项解决那些载入费时的列表项在列表滚动时的性能问题,本例介绍如果编写一个高效的List Adapter ,其实也不是什么特别的技术,主要是:

重用getView 传入参数convertView ,避免多次从XML中展开View。
设计了一个ViewHolder,用来存放一个TextView 和ImageView,避免每次都调用findViewById。
说到底就是使用变量把一些本来需要多次调用inflate或是findViewById的对象暂存起来,下次再调用getView时,可以重用这些对象,从而提高getView 的效率。


[java] 
 public View getView(int position, 
 View convertView, ViewGroup parent) { 
 // A ViewHolder keeps references to children  
 //views to avoid unneccessary calls  
 // to findViewById() on each row.  
 ViewHolder holder; 
 
 // When convertView is not null, we can reuse  
 // it directly, there is no need  
 // to reinflate it. We only inflate a new View when  
 //the convertView supplied  
 // by ListView is null.  
 if (convertView == null) { 
 convertView = mInflater 
 .inflate(R.layout.list_item_icon_text, 
 null); 
 
 // Creates a ViewHolder and store references  
 //to the two children views  
 // we want to bind data to.  
 holder = new ViewHolder(); 
 holder.text 
 = (TextView) convertView.findViewById(R.id.text); 
 holder.icon 
 = (ImageView) convertView.findViewById(R.id.icon); 
 
 convertView.setTag(holder); 
 } else { 
 // Get the ViewHolder back to get fast  
 //access to the TextView  
 // and the ImageView.  
 holder = (ViewHolder) convertView.getTag(); 
 } 
 
 // Bind the data efficiently with the holder.  
 holder.text.setText(DATA[position]); 
 holder.icon.setImageBitmap((position & 1) == 1 
 ? mIcon1 : mIcon2); 
 
 return convertView; 

 
static class ViewHolder { 
 TextView text; 
 ImageView icon; 

 public View getView(int position,
 View convertView, ViewGroup parent) {
 // A ViewHolder keeps references to children
 //views to avoid unneccessary calls
 // to findViewById() on each row.
 ViewHolder holder;

 // When convertView is not null, we can reuse
 // it directly, there is no need
 // to reinflate it. We only inflate a new View when
 //the convertView supplied
 // by ListView is null.
 if (convertView == null) {
 convertView = mInflater
 .inflate(R.layout.list_item_icon_text,
 null);

 // Creates a ViewHolder and store references
 //to the two children views
 // we want to bind data to.
 holder = new ViewHolder();
 holder.text
 = (TextView) convertView.findViewById(R.id.text);
 holder.icon
 = (ImageView) convertView.findViewById(R.id.icon);

 convertView.setTag(holder);
 } else {
 // Get the ViewHolder back to get fast
 //access to the TextView
 // and the ImageView.
 holder = (ViewHolder) convertView.getTag();
 }

 // Bind the data efficiently with the holder.
 holder.text.setText(DATA[position]);
 holder.icon.setImageBitmap((position & 1) == 1
 ? mIcon1 : mIcon2);

 return convertView;
}

static class ViewHolder {
 TextView text;
 ImageView icon;
}

 

这里至少说明了List Adapter的getView 传入的convertView 本身是重用的,而不是每次创建了一个新的convertView。

 \

 

补充:移动开发 , Android ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,