Search code examples
androidandroid-cursoradapter

newView() in CursorAdapter is called again and again


My Code is just like the below example. It is supposed to call newView() only once, But I don't know why the heck it is being called again and again?

 public class TimeListAdapter extends CursorAdapter {
     private    static  class   ViewHolder  {
         int    nameIndex;
         int    timeIndex;
         TextView   name;
         TextView   time;
    }
  public TimeListAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
  }
  @Override
  public void bindView(View view, Context context, Cursor cursor) {
         ViewHolder holder  =   (ViewHolder)    view.getTag();
         holder.name.setText(cursor.getString(holder.nameIndex));
         holder.time.setText(cursor.getString(holder.timeIndex));
  }
  @Override
  public View newView(Context context, Cursor cursor, ViewGroup  
  p parent) {
         View   view    =   LayoutInflater.from(context).inflate    
         p (R.layout.time_row,  null);
         ViewHolder holder  =   new ViewHolder();
         holder.name    =   (TextView)  view.findViewById(R.id.task_name);
         holder.time    =   (TextView)  view.findViewById(R.id.task_time);
     holder.nameIndex   =   cursor.getColumnIndexOrThrow    
         p (TaskProvider.Task.NAME);
         holder.timeIndex   =   cursor.getColumnIndexOrThrow    
         p (TaskProvider.Task.DATE);
         view.setTag(holder);
    return view;
  }
}

For instance, I have 12 items to be displayed, newView() method is supposed to be called only once to reuse the view.(Please correct me if I am wrong).

But here it is called for at least 7 times. Am I doing anything wrong? else Something fundamentally wrong with reusing ListView using CursorAdapter?


Solution

  • Wrong! newView method is called as many time as needed to inflate the currently visible views on screen, followed by a bindView to actually set the wanted data to those newly inflated views. Then only bindView is called when a view go offscreen and a new one is appearing on scroll. That's the recycling process.

    I suppose you have 7 items displayed on screen at the same time, that's the reason why the newView method is called 7 times.