How to implement a view holder?

Solution 1:

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.

Solution 2:

You would need to write you own version of ListView to do that (which is bad). If the ListView doesn't work properly, it probably means that you are doing something wrong.

Where does the id element come from? You are getting the position in your getView() method, so you don't need to worry about exceeding list bounds. The position is linked to the element position in your list, so you can get the correct element like this:

myElements.get(position);

When the data in your list changes, you can call this:

yourAdapter.notifyDataSetChanged()

That will rebuild your list with new data (while keeping your scrolling and stuff).