2013-05-07 22 views
1

我在SO和其他網站上發現了很多有關如何用Cursor填充Spinner的答案,但他們都使用構造函數SimpleCursorAdapter(Context, int, String[], int[])來構建。似乎沒有人用API級別11和以上來描述如何實現它。如何在API級別11之後用光標填充微調器?

該API告訴我使用LoaderManager,但我不確定如何使用它。

+1

我建議實現自己的CursorAdapter而不是使用SimpleCursorAdapter。 – 2013-05-07 11:07:19

+0

感謝@DoctororDrive,您的評論是一個很好的評論。如果你花時間輕描淡寫地描述如何創建一個自定義的'CursorAdapter',你可以考慮魔術般地將它變成一個答案,你至少可以贏得25分。 – SteeveDroz 2013-05-07 14:05:04

回答

1

我會建議實現您自己的CursorAdapter而不是使用SimpleCursorAdapter。

實現CursorAdapter並不比實現任何其他適配器更困難。 CursorAdapter擴展了BaseAdapter,並且getItem(),getItemId()方法已爲您覆蓋並返回實際值。 如果您支持pre-Honeycomb,建議使用支持庫中的CursorAdapter(android.support.v4.widget.CursorAdapter)。如果你只在11之後,只需使用android.widget.CursorAdapter 注意,當你調用swapCursor(newCursor)時,你不需要調用notifyDataSetChanged();

import android.widget.CursorAdapter; 

public final class CustomAdapter 
     extends CursorAdapter 
{ 

    public CustomAdapter(Context context) 
    { 
     super(context, null, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); 
    } 


    // here is where you bind the data for the view returned in newView() 
    @Override 
    public void bindView(View view, Context arg1, Cursor c) 
    { 

     //just get the data directly from the cursor to your Views. 

     final TextView address = (TextView) view 
       .findViewById(R.id.list_item_address); 
     final TextView title = (TextView) view 
       .findViewById(R.id.list_item_title); 

     final String name = c.getString(c.getColumnIndex("name")); 
     final String addressValue = c.getString(c.getColumnIndex("address")); 

     title.setText(name); 
     address.setText(addressValue); 
    } 

    // here is where you create a new view 
    @Override 
    public View newView(Context arg0, Cursor arg1, ViewGroup arg2) 
    { 
     return inflater.inflate(R.layout.list_item, null); 
    } 

} 
2

似乎沒有人能夠描述如何使用API​​級別11及以上級別來執行此操作。

的文件呢,通過showing you a non-deprecated constructor是一樣的一個,你要使用,用int flags額外的參數。如果沒有可用的標誌值對您有用,則通過0作爲標誌。