How to implement a view holder?

Have you tried this?

public View getView(int position, View convertView, ViewGroup parent) {            

   // A ViewHolder keeps references to children views to avoid unneccessary calls            
   // to findViewById() on each row.            
   ViewHolder holder;            
   // When convertView is not null, we can reuse it directly, there is no need            
   // to reinflate it. We only inflate a new View when the convertView supplied            
   // by ListView is null.            

   if (convertView == null) {                

    convertView = mInflater.inflate(R.layout.sample, null);   
    // Creates a ViewHolder and store references to the two children views                
    // we want to bind data to.               
    holder = new ViewHolder();                
    holder.name = (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.name.setText(myElements.get(id)); 
   holder.icon.setImageBitmap( mIcon1 );

   return convertView;
  }  

static class ViewHolder {            
    TextView name;            
    ImageView icon;        
} 

If yes, what’s wrong with it?

I don’t think loading all the rows at once is a good idea. You will end up having plenty of useless Views in memory that are going to slow the application down for nothing.
Views and operations on views (like inflate, findViewById, getChild..) are expensive, you should try to reuse them as much as possible. That’s why we use ViewHolders.

Leave a Comment