gpt4 book ai didi

java - ViewHolder 模式在自定义 CursorAdapter 中正确实现?

转载 作者:IT老高 更新时间:2023-10-28 21:11:41 26 4
gpt4 key购买 nike

这是我的自定义 CursorAdapter:

public class TasksAdapter extends CursorAdapter implements Filterable {

private final Context context;

public TasksAdapter(Context context, Cursor c) {
super(context, c);
this.context = context;
}

/**
* @see android.widget.CursorAdapter#newView(android.content.Context, android.database.Cursor, android.view.ViewGroup)
*/
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(android.R.layout.simple_list_item_checked, parent, false);

ViewHolder holder = new ViewHolder();
holder.textview = (CheckedTextView)v.findViewById(android.R.id.text1);
v.setTag(holder);

return v;
}

/**
* @see android.widget.CursorAdapter#bindView(android.view.View, android.content.Context, android.database.Cursor)
*/
@Override
public void bindView(View view, Context context, Cursor cursor) {

ViewHolder holder = (ViewHolder)view.getTag();
int titleCol = cursor.getColumnIndexOrThrow(Tasks.TITLE);
int completedCol = cursor.getColumnIndexOrThrow(Tasks.COMPLETED);

String title = cursor.getString(titleCol);
boolean completed = Util.intToBool(cursor.getInt(completedCol));

holder.textview.setText(title);
holder.textview.setChecked(completed);
}

/**
* @see android.widget.CursorAdapter#runQueryOnBackgroundThread(java.lang.CharSequence)
*/
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {

StringBuffer buffer = null;
String[] args = null;

if (constraint != null) {
buffer = new StringBuffer();
buffer.append("UPPER (");
buffer.append(Tasks.TITLE);
buffer.append(") GLOB ?");
args = new String[] { "*" + constraint.toString().toUpperCase() + "*" };
}

Cursor c = context.getContentResolver().query(Tasks.CONTENT_URI,
null, (buffer == null ? null : buffer.toString()), args,
Tasks.DEFAULT_SORT_ORDER);

c.moveToFirst();
return c;
}

/**
* @see android.widget.CursorAdapter#convertToString(android.database.Cursor)
*/
@Override
public CharSequence convertToString(Cursor cursor) {
final int titleCol = cursor.getColumnIndexOrThrow(Tasks.TITLE);
String title = cursor.getString(titleCol);
return title;
}

static class ViewHolder {
CheckedTextView textview;
}

}

这是否属于 ViewHolder 模式的约束?我不确定,因为这是一个没有 getView 的 CursorAdapter。如果有任何问题或建议,请指出来。

最佳答案

CursorAdapter 不会在每次需要新行时调用 newView;如果它已经有一个View,它会调用bindView,所以创建的view实际上是复用的。

也就是说,正如 Joseph 在评论中指出的那样,您仍然可以使用 ViewHolder 以避免重复调用 findViewById

如果您仍然关心效率,请查看 SimpleCursorAdapter实现,它使用 WeakHashMap(WeakReferences 的映射):

WeakHashMap<View, View[]> mHolders = new WeakHashMap<View, View[]>();

关于java - ViewHolder 模式在自定义 CursorAdapter 中正确实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4567969/

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