【问题标题】:Why is CursorAdapter different from BaseAdapter?为什么 CursorAdapter 与 BaseAdapter 不同?
【发布时间】:2013-09-01 18:51:28
【问题描述】:

我想问一下为什么CursorAdapter 将创建视图和填充数据的过程拆分为newView()bindView()BaseAdapter 只对getView() 这样做?

【问题讨论】:

    标签: android baseadapter android-cursoradapter


    【解决方案1】:

    来自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() 函数,从源代码中你可以看到不需要。

    【讨论】:

    • CursorAdapter 也关闭了以前使用的 Cursor(看看 changeCursor(Cursor) 方法)。这是有用的还是糟糕的,取决于你的情况))
    【解决方案2】:

    如果您查看CurosrAdapter 源代码,您可以看到,在getView 方法中,newViewbindView 方法都被使用。方法newView只在没有视图的情况下执行,这样可以省去一些对象的创建。方法bindView总是被调用,它的目的是更新视图数据。

    【讨论】:

      猜你喜欢
      • 2011-12-31
      • 1970-01-01
      • 2021-09-16
      • 2014-10-31
      • 1970-01-01
      • 2016-07-24
      • 2019-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多