原文地址:http://www.eoeandroid.com/thread-321547-1-1.html
为什么要单独拿出来写,太好用了。
常用写法:
private static class ViewHolder{
private TextView allcity;
private TextView citybutton;
}
ViewHolder holder = null;
if(convertView == null){
holder = new ViewHolder();
convertView=LayoutInflater.from(context).inflate(R.layout.food_restaurant_dishes_item, null);
holder.img_dishesa = (ImageView) convertView.findViewById(R.id.img_dishesa);
<pre name="code" class="java"> convertView.setTag(holder);
}else{holder = (ViewHolder) convertView.getTag();}
简洁写法: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()这么写:
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;
}
简单描述:使用SparseArray与ViewHolder相比有损耗,但这些内存损耗可以忽略。除非有性能瓶颈,再进行优化。
关于SparseArray的用法:
参考:http://blog.csdn.net/xyz_fly/article/details/7931943
1、使用场景:
SparseArray<E>替代HashMap<Integer, E>时,性能更佳。
2、用法
2.1构造:它和一般的list一样,可预先设置容器大小,默认大小是10.
public SparseArray() {
this(10);
}
public SparseArray(int initialCapacity) {
......
}
2.2增:两个方法
public void put(int key, E value)
public void append(int key, E value)
存储数据时,采用了二分法,以下是源码:
private static int binarySearch(int[] a, int start, int len, int key) {
int high = start + len;
int low = start - 1;
while (high - low > 1) {
int guess = (high + low) / 2;
if (a[guess] < key) {
low = guess;
continue;
}
high = guess;
}
if (high == start + len)
return start + len ^ 0xFFFFFFFF;
if (a[high] == key) {
return high;
}
return high ^ 0xFFFFFFFF;
}
所以,它存储的数值都是按键值从小到大的顺序排列的。
2.3查:有两个方法可以取值public E get(int key)
public E get(int key, E valueIfKeyNotFound)
最后一个从传参的变量名就可看出,传入的是找不到时候的返回值。
查看第几个位置的键:
public int keyAt(int index)
查看第几个位置的值:
public E valueAt(int index)
查看键所在位置(由于采用二分法查找键的位置,所有没有的话,返回小于0的数值,而不是-1,返回的负数表示它在哪个位置就找不到了。即如果你存了5个,查找的键大于5个值的话,返回就是-6):
public int indexOfKey(int key)
查看值所在位置,没有的话返回-1:
public int indexOfValue(E value)
2.4删:
public void delete(int key)
public void remove(int key)
delete()和remove()相同,remove()中调用了delete()
public void removeAt(int index)
public void clear()
clear()是清除全部
2.5改:public void setValueAt(int index, E value)
public void put(int key, E value)
put()如果键不存在,就会变为添加新键值对。