ViewHoder如下:
1 | public class ViewHolder { |
2 | // I added a generic return type to reduce the casting noise in client code |
3 | @SuppressWarnings("unchecked") |
4 | public static <T extends View> T get(View view, int id) { |
5 | SparseArray<View> viewHolder = (SparseArray<View>) view.getTag(); |
6 | if (viewHolder == null) { |
7 | viewHolder = new SparseArray<View>(); |
8 | view.setTag(viewHolder); |
9 | } |
10 | View childView = viewHolder.get(id); |
11 | if (childView == null) { |
12 | childView = view.findViewById(id); |
13 | viewHolder.put(id, childView); |
14 | } |
15 | return (T) childView; |
16 | } |
17 | } |
在getView里这样
1 | @Override |
2 | public View getView(int position, View convertView, ViewGroup parent) { |
3 | |
4 | if (convertView == null) { |
5 | convertView = LayoutInflater.from(context) |
6 | .inflate(R.layout.banana_phone, parent, false); |
7 | } |
8 | |
9 | ImageView bananaView = ViewHolder.get(convertView, R.id.banana); |
10 | TextView phoneView = ViewHolder.get(convertView, R.id.phone); |
11 | |
12 | BananaPhone bananaPhone = getItem(position); |
13 | phoneView.setText(bananaPhone.getPhone()); |
14 | bananaView.setImageResource(bananaPhone.getBanana()); |
15 | |
16 | return convertView; |
17 | } |