【发布时间】:2013-09-01 18:51:28
【问题描述】:
我想问一下为什么CursorAdapter 将创建视图和填充数据的过程拆分为newView() 和bindView() 而BaseAdapter 只对getView() 这样做?
【问题讨论】:
标签: android baseadapter android-cursoradapter
我想问一下为什么CursorAdapter 将创建视图和填充数据的过程拆分为newView() 和bindView() 而BaseAdapter 只对getView() 这样做?
【问题讨论】:
标签: android baseadapter android-cursoradapter
来自CursorAdapter.java的源代码,CursorAdapter扩展BaseAdapter。
并且可以看到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;
}
它做我们通常在getView() 中所做的事情(如果 convertView 为空,则膨胀视图,否则重用视图),所以它只是为了让开发人员更容易或强制用户使用 ViewHolder 模式。
PS:有些开发者在 newView() 实现中调用了 bindViews() 函数,从源代码中你可以看到不需要。
【讨论】:
如果您查看CurosrAdapter 源代码,您可以看到,在getView 方法中,newView 和bindView 方法都被使用。方法newView只在没有视图的情况下执行,这样可以省去一些对象的创建。方法bindView总是被调用,它的目的是更新视图数据。
【讨论】: