Adapter(16)关于Adapter中getView与ViewHolder的更正

更正:

之前一直喜欢在getview里不用holder,而是直接用contentView.findViewById(xxx); 这和种写法不好,每次都要findview。 

下面是正确的写法:

 1         /**
 2          * Make a view to hold each row.
 3          *
 4          * @see android.widget.ListAdapter#getView(int, android.view.View,
 5          *      android.view.ViewGroup)
 6          */
 7         public View getView(int position, View convertView, ViewGroup parent) {
 8             // A ViewHolder keeps references to children views to avoid unneccessary calls
 9             // to findViewById() on each row.
10             ViewHolder holder;
11 
12             // When convertView is not null, we can reuse it directly, there is no need
13             // to reinflate it. We only inflate a new View when the convertView supplied
14             // by ListView is null.
15             if (convertView == null) {
16                 convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
17 
18                 // Creates a ViewHolder and store references to the two children views
19                 // we want to bind data to.
20                 holder = new ViewHolder();
21                 holder.text = (TextView) convertView.findViewById(R.id.text);
22                 holder.icon = (ImageView) convertView.findViewById(R.id.icon);
23 
24                 convertView.setTag(holder);
25             } else {
26                 // Get the ViewHolder back to get fast access to the TextView
27                 // and the ImageView.
28                 holder = (ViewHolder) convertView.getTag();
29             }
30 
31             // Bind the data efficiently with the holder.
32             holder.text.setText(DATA[position]);
33             holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
34 
35             return convertView;
36         }
37 
38         static class ViewHolder {
39             TextView text;
40             ImageView icon;
41         }

 

原理

1,数据过多怎么办?

  数据过多时,不用给每条数据都new一个view,可利用convertView,如果它不空,就可以直接更新它显示的数据为第position条就可,空再构造它。

2,View的setTag方法是什么回事?

  setTag方法是干什么的,SDK解释为

Tags
Unlike IDs, tags are not used to identify views. Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure.

  Tag不像ID是用标示view的。Tag从本质上来讲是就是相关联的view的额外的信息。它们经常用来存储一些view的数据,这样做非常方便而不用存入另外的单独结构。

3,ViewHolder怎么回事? 

  如果convertView不空,就可以直接更新数据了,那么就要TextView t = convertView.findViewById(xxx),然后再更新t,

  如果把convertView构造时已经find到的的TextView 以额外数据的形式保存在convertView的tag中,下次就不用findViewById了。

 

posted @ 2016-04-29 16:06  f9q  阅读(226)  评论(0)    收藏  举报