2011-06-16 51 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