2012-04-16 73 views
1

我有一個SQLite查詢,返回Cursor。我想通過實施一個MatrixCursor(爲了保持點擊時自動選擇第一項實際數據)而向Cursor添加一些額外的行。然後我想將它們映射到SimpleCursorAdapter。我一直在閱讀帖子(和代碼),但仍然對我如何將其編碼到我現有的代碼下面。如何爲微調器實現MatrixCursor?

Cursor cursor = myDB.query(DATABASE_TABLE_NAME, resultColumns, whereClause, 
      whereArgs, null, null, null, null); 

    // Create Spinner View object from layout resource 
    Spinner spinner = (Spinner) findViewById(R.id.spinner); 

    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_spinner_item, // Use a template 
                // that displays a 
                // text view 
      cursor, // Give the cursor to the adapter 
      new String[] {"ename"}, // Map the NAME column in the 
               // people database to... 
      new int[] {android.R.id.text1}); 

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    spinner.setAdapter(adapter); 
    spinner.setOnItemSelectedListener(new MyOnItemSelectedListener()); 

回答

5

如果你想從一個簡單的Cursor建立MatrixCursor你必須解析整個初始Cursor並添加你想要的行:

//... 
    MatrixCursor mc = new MatrixCursor(resultColumns); 
    // add extra rows, this will probably not work if you want to insert them 
    // between the initial cursor rows because of the _id column that need autoincrement values 
    mc.addRow(new Object[] { new Long(-2), "Extra name1" }); 
    mc.addRow(new Object[] { new Long(-1), "Extra name2" }); 
    // I don't know what your cursor holds, I assumed you have the _id column(long value) 
    // and a name(String value) 
    int size = cursor.getCount(); 
    for (int i = 0; i < size; i++) { 
     cursor.moveToPosition(i); 
      mc.addRow(new Object[] { 
      cursor.getLong(cursor.getColumnIndex(/*the _id column*/)), 
      cursor.getString(cursor.getColumnIndex(/* the name column(ename?!?)*/)) }); 
    } 
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, 
      android.R.layout.simple_spinner_item, mc, new String[] {"ename"}, new int[] {android.R.id.text1}); 
//... 

如果你這樣做只是爲了當Spinner顯示時避免OnItemSelectedListener發射,也許你可以有另一種方法。例如在你的聽衆:

//boolean status = true; flag in MyOnItemSelectedListener 

    @Override 
    public void onItemSelected(AdapterView<?> parent, View view, 
      int position, long id) { 
     if (status) { 
      status = false;// this is the first listener trigger so you probably want to ignore it 
      return; 
     } 
     // do stuff here 
    } 

注:我不知道以上的解決方案有多好。如果你看起來有可能更好的解決這個Spinner相關的問題。

+0

非常感謝你的幫助 – j2me 2012-05-16 06:45:01

+0

使用'Long.valueOf(-2)'而不是'new Long(-2)'。 – bancer 2012-11-02 13:49:17