如果对效率要求比较高的话可以采用这种办法,唯一的缺点就是多了一个内部类ViewHolder。
public View getView(int pos, View convertView, ViewGroup parent){
ViewHolder holder;
if (convertView == null) {
holder=new ViewHolder();
convertView = mInflater.inflate(R.layout.list_item, null);
holder.text = (TextView) convertView.findViewById( R.id.text));
holder.icon = (ImageView) convertView.findViewButId( R.id.icon));
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(DATA[pos]);
holder.icon.setImageBitmap((pos & 1) == 1 ? mIcon1 : mIcon2);
return convertView;
}
static class ViewHolder {
TextView text;
ImageView icon;
}
但这样需要的Adapter一多,每次都要将代码repeat。 有一种简洁的写法分享给大家。
ViewHolder这么写(只提供一个静态方法)
public class ViewHolder {
// I added a generic return type to reduce the casting noise in client code
@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;
}
}
在getView里这样
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(context)
.inflate(R.layout.banana_phone, parent, false);
}
ImageView bananaView = ViewHolder.get(convertView, R.id.banana);
TextView phoneView = ViewHolder.get(convertView, R.id.phone);
BananaPhone bananaPhone = getItem(position);
phoneView.setText(bananaPhone.getPhone());
bananaView.setImageResource(bananaPhone.getBanana());
return convertView;
}
把这个ViewHolder类加入自己的utils,一劳永逸了以后。注意SparseArray这个知识点,优化过的存储integer和object键值对的hashmap。
下面是一个github上的开源项目小工具,更cool更简洁! 核心同样是使用SparseArray存储id+view,但更巧妙的是使用Builder模式进一步封装了常用的控件方法,进一步简化了代码~
地址是
https://github.com/JoanZapata/base-adapter-helper