2011-06-16 61 views
1

我该如何去扩展SimpleCursorAdapter允许以下:的Android SimpleCursorAdapter与LoaderManager/CursorLoader

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

我弄不清楚是如何动态地改变SimpleCursorAdapter来根据游标结果显示正确的列数。我有来自Cursor.getColumnNames()的列名,并且我可以在SimpleCursorAdapter构造函数的参数中将这些列引入到String []中。但是,如何动态创建int参数所需的视图? SimpleCursorAdapter只是不适用于这种情况,因为它正在寻找由xml布局文件构建的id?我应该继续使用带有CursorLoader的LoaderManager吗?这是一个更灵活的解决方案吗?

回答

3

您应该转而使用带有CursorLoader的LoaderManager。

正如SimpleCursorAdapter说,在部分:

此构造已被弃用。不鼓励使用此选项,因为它会导致在应用程序的UI线程上执行游标查询,因此可能导致响应性较差甚至出现应用程序无响应错误。

+2

但他们有第二个构造函数,现在不被弃用,是否正确? – theblang 2013-11-20 15:54:16

+0

@mattblang。什么不被弃用? – 2014-01-02 19:51:21

+3

@IgorGanapolsky:有[带有标志参数的构造函数](http://developer.android.com/reference/android/widget/SimpleCursorAdapter.html#SimpleCursorAdapter%28android.content.Context,%20int,%20android.database.Cursor ,%20java.lang.String [],%20int [],%20int%29),它只表示“标准构造函数”,并且没有弃用信息。 – akavel 2014-01-08 23:39:52

0

使用LoaderManager/CursorLoader无法解决您在填充SimpleCursorAdapter时遇到的问题。但是您应该使用它来将您的列表填充到UI线程中,并有效地处理活动的配置更改。

这里是如何光标列名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个TextViews映射在你的布局文件

所以,你的RES /布局/ 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这是你需要做的一个很好的例子。

希望有帮助!

+0

为什么有人会使用TableLayout? GridLayout是未来的潮流。 – 2014-01-02 19:53:01

相关问题