use*_*075 15 android android-adapter android-cursoradapter
当重写ArrayAdapter我知道使用这样的模式是正确的:
if(view != null){
...create new view setting fields from data
}else
return view; //reuse view
Run Code Online (Sandbox Code Playgroud)
使用CursorAdapters的这种模式也是正确的吗?我的问题是我有一个根据光标字段可以是红色或蓝色的文本颜色,所以我不希望任何错误像一个需要蓝色字段的单元格上的红色.我的bindView代码是这样的:
if(c.getString(2).equals("red"))
textView.setTextColor(<red here>);
else
textView.setTextColor(<blue here>);
Run Code Online (Sandbox Code Playgroud)
如果我重复使用视图,我可以确定红色是红色,而蓝色是蓝色吗?
Nam*_*ung 37
在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;
}
Run Code Online (Sandbox Code Playgroud)
如果您想要进一步优化,请使用以下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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17034 次 |
| 最近记录: |