2010-02-03 51 views
10

我對Android開發(2天前開始)頗爲陌生,已經完成了大量教程。我從Android SDK中的NotePad練習(Link to tutorial)構建測試應用程序,並根據我稱爲「notetype」的數據庫字段的內容顯示不同圖像。我希望此圖像在每個記事本條目之前出現在列表視圖中。Android:根據數據庫字段數據更改ImageView src

在我的.java文件中的代碼是:

private void fillData() { 
    Cursor notesCursor = mDbHelper.fetchAllNotes(); 

    notesCursor = mDbHelper.fetchAllNotes(); 
    startManagingCursor(notesCursor); 

    String[] from = new String[]{NotesDbAdapter.KEY_NOTENAME, NotesDbAdapter.KEY_NOTETYPE}; 

    int[] to = new int[]{R.id.note_name, R.id.note_type}; 

    // Now create a simple cursor adapter and set it to display 
    SimpleCursorAdapter notes = 
      new SimpleCursorAdapter(this, R.layout.notes_row, notesCursor, from, to); 
    setListAdapter(notes); 
} 

而且我的佈局xml文件(notes_row.xml)看起來是這樣的:

<ImageView android:id="@+id/note_type" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content" 
      android:src="@drawable/default_note"/> 
<TextView android:id="@+id/note_name" 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content"/> 

我真的不知道我怎麼樣d取決於所選音符的類型,取出右側的可拖動畫面。目前我有能力從Spinner中選擇類型,因此存儲在數據庫中的是整數。我已經創建了一些與這些整數相對應的圖像,但它似乎沒有提到。

任何幫助,將不勝感激。如果您需要更多信息,請讓我知道。

回答

24

您可能想嘗試使用ViewBinder。 http://d.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html

這個例子應該有所幫助:

private class MyViewBinder implements SimpleCursorAdapter.ViewBinder { 

    public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
     int viewId = view.getId(); 
     switch(viewId) { 
      case R.id.note_name: 

       TextView noteName = (TextView) view; 
       noteName.setText(Cursor.getString(columnIndex)); 

      break; 
      case R.id.note_type: 

       ImageView noteTypeIcon = (ImageView) view; 

       int noteType = cursor.getInteger(columnIndex); 
       switch(noteType) { 
        case 1: 
         noteTypeIcon.setImageResource(R.drawable.yourimage); 
        break; 
        case 2: 
         noteTypeIcon.setImageResource(R.drawable.yourimage); 
        break; 
        etc… 
       } 

      break; 
     } 
    } 

}

然後將其與

note.setViewBinder(new MyViewBinder()); 
+0

優秀添加到您的適配器 - 完美的作品。不能要求更簡單的解決方案:)。您真誠的感謝! – Butteredchops

+0

偉大的答案!謝謝! –

+0

我想補充一點,你不必覆蓋'setViewValue'中的所有情況,只是爲了ImageView。對於所有其他視圖,您應該只返回'false',在這種情況下,Android將應用您提供給SimpleCursorAdapter的普通綁定。 – damluar

相關問題