无意中注意到了view.setTag(Object tag)方法.
Tag在View中是很有作用的属性,API中这样描述的:
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的数据,这样做非常方便而不用存入另外的单独结构。
其实,我们在优化listview的getView()方法中就用到了setTag()和getTag()。
摘取代码段如下:
ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(SongsActivity.this).inflate( R.layout.music_item, null); ImageView pImageView = (ImageView) convertView .findViewById(R.id.albumPhoto); viewHolder = new ViewHolder(pImageView, pTitle, pDuration, pArtist); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); }
setTag还有带2个参数的形式,setTag(key, tag),暂时不做讨论。