15

当覆盖 ArrayAdapter 我知道使用这样的模式是正确的:

if(view != null){
   ...create new view setting fields from data 
}else
  return view; //reuse view

将这种模式与 CursorAdapters 一起使用是否也正确?我的问题是我有一个文本颜色,根据光标字段可以是红色或蓝色,所以我不希望在有一个需要蓝色字段的单元格上出现任何错误,例如红色。我的 bindView 代码是这样的:

if(c.getString(2).equals("red"))
      textView.setTextColor(<red here>);
   else
      textView.setTextColor(<blue here>);

如果我重用视图,我可以确定红色变为红色,而蓝色变为蓝色吗?

4

2 回答 2

37

CursorAdapter中,您在 中获取布局并在中newView绑定数据bindViewCursorAdapter已经做了重用模式,getView所以你不必再做一次。下面是原始getView源代码。

  public View getView(int position, View convertView, ViewGroup parent) {
    if (!mDataValid) {
        throw new IllegalStateException("this should only be called when the cursor is valid");
    }
    if (!mCursor.moveToPosition(position)) {
        throw new IllegalStateException("couldn't move cursor to position " + position);
    }
    View v;
    if (convertView == null) {
        v = newView(mContext, mCursor, parent);
    } else {
        v = convertView;
    }
    bindView(v, mContext, mCursor);
    return v;
}

如果您想进一步优化,请使用ViewHolder Pattern以下示例:创建标签newView并检索bindView

    public class TimeListAdapter extends CursorAdapter {
     private LayoutInflater inflater;
     private    static  class   ViewHolder  {
         int    nameIndex;
         int    timeIndex;
         TextView   name;
         TextView   time;
    }
  public TimeListAdapter(Context context, Cursor c, int flags) {
    super(context, c, flags);
  this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
  }
  @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    =   inflater.inflate(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 
         (TaskProvider.Task.NAME);
         holder.timeIndex   =   cursor.getColumnIndexOrThrow    
         (TaskProvider.Task.DATE);
         view.setTag(holder);
    return view;
  }
}
于 2012-09-01T03:45:29.273 回答
2

是的,getViewis inAdapter并且不依赖于ArrayAdapternor CursorAdapter

回收始终是一个好习惯。确保您的代码在每种情况下都设置颜色。

于 2012-08-31T22:50:31.387 回答