Chrisの梳羽之礁

A look of quick intelligence and soft refinement
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Adapter基础(未完)

Posted on 2011-01-06 14:50  Chrisfang6  阅读(269)  评论(0编辑  收藏  举报

Adapter的作用,顾名思义,作为适配器,在Android中向调用者(如List等)提供整合了数据的View对象。

其主要方法是getView()。该方法返回View对象给需要的调用者(比如List)。怀疑该方法在List布局的时候被调用(还未找到源码)。比如List布局时发现一屏需要插入10个View,就调用Adapter.getView()共10次。

注意:getView()的第二个参数View很重要,如果由List提供了View过来,则无需再创建新的View,直接使用就好。

 

View的回收??

 

如何高效使用Adapter?以下转自How you create your view for listview on Android?

How you create your view for listview on Android?
There have three versions of getView() function,
the first version is a slow way,and the last is the fastest one.

Version 1:

public View getView(int position, View convertView, ViewGroup parent) {
     View item = mInflater.inflate(R.layout.list_item_icon_text, null);
      ((TextView) item.findViewById(R.id.text)).setText(DATA[position]);
      ((ImageView) item.findViewById(R.id.icon)).setImageBitmap(
     (position & 1) == 1 ? mIcon1 : mIcon2);
      return item;
 }

 

Version 2:

public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
      convertView = mInflater.inflate(R.layout.item, parent, false);
    }
    ((TextView) convertView.findViewById(R.id.text)).setText(DATA[position]);
     ((ImageView) convertView.findViewById(R.id.icon)).setImageBitmap(
     (position & 1) == 1 ? mIcon1 : mIcon2);
     return convertView;
 }


Version 3: the fast way for getView function.

static class ViewHolder {
  TextView text;
  ImageView icon;
}

public View getView(int position, View convertView, ViewGroup parent) {
   ViewHolder holder;

  if (convertView == null) {
     convertView = mInflater.inflate(R.layout.list_item_icon_text,parent, false);
     holder = new ViewHolder();
     holder.text = (TextView) convertView.findViewById(R.id.text);
     holder.icon = (ImageView) convertView.findViewById(R.id.icon);
     convertView.setTag(holder);
   } else {
     holder = (ViewHolder) convertView.getTag();
   }

   holder.text.setText(DATA[position]);
   holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
   return convertView;

}

 

The last version use setTag() and getTag() to get a more high performance,
if you use the first or second version of getView(), it is the time to refactoring your code to the third version.

 

参考:

1. Android Adapter 接口中几个方法的研究

2. Android-Adapter应用总结 — Windows Live

3. How you create your view for listview on Android?