ではCursorAdapter
、 でレイアウトを取得し、newView
でデータをバインドしますbindView
。CursorAdapter
すでにパターンを再利用している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
は、次の例を使用します: Create tag in newView
and retrieve inbindView
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;
}
}