ViewHolder的作用和简洁写法
ViewHolder的作用
ViewHolder是用来减少findViewById次数的,它只需findViewById有限次后,在列表滚动过程中不断复用ViewHolder中已经缓存的View,提高列表滚动的流畅性。
常规写法 :
- 在Adapter代码中,创建一个包含list item中所有控件的viewHolder类
- 当convertView为空时,new一个viewHolder类,然后用findViewById将list item中的控件找到 ,把ViewHolder作为TAG设置给convertView
- 不为空,直接复用ViewHolder
class ViewHolder{
public TextView title;
public TextView time;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder Holder;
if(convertView == null){
convertView = inflate().inflate(R.layout.item,null);
Holder = new ViewHolder();
Holder.title = (TextView)convertView.findViewById(R.id.title);
Holder.time = (ImageView)convertView.findViewById(R.id.time);
convertView.setTag(Holder);
} else{
Holder = (ViewHolder)convertView.getTag();
}
viewHolder.title.setText("哈哈");
viewHolder.time.setText("5:20");
return convertView;
}
简洁且通用写法
创建了一个ViewHolder类,在类中提供了一个静态方法get(),方法的参数有两个,第一个是list item的layout对应的View,即适配器类中getView()方法中的convertView,第二个参数为整型的id,即list item中某个控件的id值
public class ViewHolder {
@SuppressWarnings("unchecked")
public static <T extends View> T get(View view, int id){
SparseArray<View> viewHolder = (SparseArray<View>) view.getTag();
if(viewHolder == null){
viewHolder = new SparseArray<View>();
view.setTag(viewHolder);
}
View childView = viewHolder.get(id);
if(childView == null){
childView = view.findViewById(id);
viewHolder.put(id, childView);
}
return (T) childView;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflate().inflate(R.layout.item,null);
}
TextView title = ViewHolder.get(convertView, R.id.title);
TextView time = ViewHolder.get(convertView, R.id.time);
title.setText("哈哈");
time.setText("5:20");
return convertView;
}