原因就是:
1. 使用convertView可以避免重复地调用inflate
2. 使用ViewHolder可以避免重复地调用findViewById
下面的getView代码来自于
- development/samples/ApiDemos/src/com/example/android/apis/view/List14.java
- /**
- * Make a view to hold each row.
- *
- * @see android.widget.ListAdapter#getView(int, android.view.View,
- * android.view.ViewGroup)
- */
- public View getView(int position, View convertView, ViewGroup parent) {
- // A ViewHolder keeps references to children views to<span style="color:#ff0000;"> avoid unneccessary calls
- // to findViewById()</span> on each row.
- ViewHolder holder;
- // When convertView is not null, we can reuse it directly, <span style="color:#ff0000;">there is no need
- // to reinflate it.</span> We only inflate a new View when the convertView supplied
- // by ListView is null.
- if (convertView == null) {
- convertView = mInflater.inflate(R.layout.list_item_icon_text, null);
- // Creates a ViewHolder and store references to the two children views
- // we want to bind data to.
- holder = new ViewHolder();
- holder.text = (TextView) convertView.findViewById(R.id.text);
- holder.icon = (ImageView) convertView.findViewById(R.id.icon);
- convertView.setTag(holder);
- } else {
- // Get the ViewHolder back to get fast access to the TextView
- // and the ImageView.
- holder = (ViewHolder) convertView.getTag();
- }
- // Bind the data efficiently with the holder.
- holder.text.setText(DATA[position]);
- holder.icon.setImageBitmap((position & 1) == 1 ? mIcon1 : mIcon2);
- return convertView;
- }