2014-10-11 25 views
18

我到目前爲止沒有谷歌解決方案,以取代我的項目中的列表視圖,因爲我需要使用與sqlite鏈接的遊標。是否有可能使CursorAdapter在recycleview中設置,就像ListView一樣?

爲遵循舊的方式: listview.setAdapter(cursorAdapter)這樣,我可以讓光標來處理數據,數據庫

但現在,recycleview.setAdapter(recycleview.adapter)它不承認延伸BaseAdapter

所以任何人都可以將適配器幫幫我?

+1

見我的答案在這裏: http://stackoverflow.com/a/27732748/1371730 尼斯把戲:)的 – nbtk 2015-01-01 17:01:25

+0

可能的複製[在數據庫中使用recyclerview](http://stackoverflow.com/questions/26517855/using-the-recyclerview-with-a-database) – e4c5 2015-10-15 06:27:58

回答

7

新的RecyclerView與新的RecyclerView.Adapter基類一起使用。 所以它不適用於CursorAdapter

目前有沒有默認實現RecyclerView.Adapter可用。

可能隨着官方發佈,Google會添加它。

+1

是的,我在github中找到了一個解決方案,但官方發佈會更好在各方面,我最好等一等。 – machinezhou 2014-10-14 03:34:14

+1

@machinezhou你可以分享github項目嗎? – josedlujan 2015-11-15 04:18:45

+0

@josedlujan這裏是github項目的鏈接https://gist.github.com/skyfishjy/443b7448f59be978bc59 – 2015-11-24 14:27:54

31

自己做起來其實很簡單:

public class CursorAdapter extends RecyclerView.Adapter<ViewHolder>{ 

    Cursor dataCursor; 

    @Override 
    public int getItemCount() { 
     return (dataCursor == null) ? 0 : dataCursor.getCount(); 
    } 


    public void changeCursor(Cursor cursor) { 
     Cursor old = swapCursor(cursor); 
     if (old != null) { 
      old.close(); 
     } 
     } 

    public Cursor swapCursor(Cursor cursor) { 
     if (dataCursor == cursor) { 
      return null; 
     } 
     Cursor oldCursor = dataCursor; 
     this.dataCursor = cursor; 
     if (cursor != null) { 
      this.notifyDataSetChanged(); 
     } 
     return oldCursor; 
     } 

    private Object getItem(int position) { 
     dataCursor.moveToPosition(position); 
     // Load data from dataCursor and return it... 
     } 

} 
+1

呃,這不是我的好朋友,我的確在github上發現了一個項目,其中cursorAdapter是由開發人員自己實現的。但這並不容易,我不確定它是否會出現一個錯誤或意外的事情。所以由於我自己的能力和穩定性問題,我寧願等待正式發佈。 – machinezhou 2014-10-31 04:25:18

+2

@machinezhou我不認爲他們會爲它增加一個正式版本,到目前爲止這對我來說一直是完美的工作 – nyx 2015-01-12 12:13:03

+0

我感覺得到的是,由於「不」數據庫在UI線程上工作「,自從CursorLoader以來他們一直在推動這些工作。 無論如何,就這裏的解決方案而言,繼續我見過的其他實現,您可能需要檢查移動光標或光標狀態導致的潛在錯誤。到目前爲止,我所見過的實現只是在這種情況下拋出異常,這對我來說似乎不太合適。 – Tarkenfire 2015-01-21 12:50:07

相關問題