1

我该如何扩展 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 吗?这会是一个更灵活的解决方案吗?

4

2 回答 2

3

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

正如SimpleCursorAdapter部分所说:

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

于 2011-11-01T23:28:52.100 回答
0

使用 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。

希望有帮助!

于 2012-06-30T04:32:15.007 回答