【问题标题】:Android SimpleCursorAdapter vs. LoaderManager/CursorLoaderAndroid SimpleCursorAdapter 与 LoaderManager/CursorLoader
【发布时间】:2011-09-16 07:51:36
【问题描述】:

如何扩展 SimpleCursorAdapter 以允许以下操作:

2 个片段,一个菜单一个细节。 Menu ListFragment 是一个表列表,详细 ListFragment 显示了对这些表的查询结果。详细信息 ListFragment 从菜单 ListFragment 中的选择中获取表名。在 onActivityCreated 的细节 ListFragment 里面,所有的记录都被选中到一个游标中。此游标被传递到 SimpleCursorAdapter。然后将此 SimpleCursorAdapter 设置为详细信息 ListFragment 的 ListAdapter。

我不知道如何根据光标结果动态更改 SimpleCursorAdapter 以显示正确的列数。我有来自 Cursor.getColumnNames() 的列名,我可以从 SimpleCursorAdapter 构造函数的参数中将它们放入 String[] 中。但是如何动态创建 int to 参数所需的视图? SimpleCursorAdapter 是否会不适用于这种情况,因为它正在寻找基于 xml 布局文件构建的 id?我应该继续使用带有 CursorLoader 的 LoaderManager 吗?这会是一个更灵活的解决方案吗?

【问题讨论】:

    标签: android android-loadermanager


    【解决方案1】:

    您应该继续使用带有 CursorLoader 的 LoaderManager。

    正如SimpleCursorAdapter 部分所说:

    此构造函数已弃用。不鼓励使用此选项,因为它会导致在应用程序的 UI 线程上执行游标查询,从而导致响应速度不佳甚至应用程序无响应错误。

    【讨论】:

    • 但是他们现在有了第二个构造函数,它没有被弃用,对吗?
    • @mattblang。什么不被弃用?
    • @IgorGanapolsky:有a constructor with flags argument,上面写着“标准构造函数”,没有弃用信息。
    【解决方案2】:

    使用 LoaderManager/CursorLoader 并不能解决填充 SimpleCursorAdapter 的问题。但是您当然应该使用它来从 UI 线程中填充您的列表并有效地处理您的活动的配置更改。

    下面是如何为每一行将 Cursor 列名映射到 TextViews:

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), 
         R.layout.custom_row,
         null, 
         new String[] { "columnName_1", "columnName_2", "columnName_3" }, 
         new int[] { R.id.txtCol1, R.id.txtCol2, R.id.txtCol3 }, 0);
    setListAdapter(adapter);
    

    这会将光标中的 3 列映射到布局文件中的 3 个 TextView

    所以你的 res/layout/custom_row.xml 可以如下所示:

    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:orientation="horizontal">
         <TextView android:id="@+id/txtCol1"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Your column 1 text will end up here!" />
    
         <TextView android:id="@+id/txtCol2"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Your column 2 text will end up here!" />
    
         <TextView android:id="@+id/txtCol3"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Your column 3 text will end up here!" />
    </LinearLayout>
    

    在现实世界中.. 使用 TableLayout 可能会发现更好的结果。

    对于CursorLoader,请看http://developer.android.com/guide/components/loaders.html 它们提供了一个很好的例子,说明你需要为 CursorAdapters 使用 CursorLoader 和 LoaderManager。

    希望有帮助!

    【讨论】:

    • 为什么有人会使用 TableLayout? GridLayout 是未来的潮流。
    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多