gpt4 book ai didi

android - CursorAdapter bindView 优化

转载 作者:IT老高 更新时间:2023-10-28 23:39:04 27 4
gpt4 key购买 nike

当覆盖 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>);

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

最佳答案

CursorAdapter中,在newView中获取布局,在bindView中绑定(bind)数据。 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 进一步优化,这里是示例:在 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;
}
}

关于android - CursorAdapter bindView 优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12223293/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com