1

我試圖使用與ViewBinder一個SimpleCursorAdapterListView添加背景顏色爲TextView,但它不工作:使用ViewBinder自定義ListView項與TextView的

listrow.xml:

<TextView 
    android:id="@+id/catcolor" 
    android:layout_width="4dp" 
    android:layout_height="match_parent" 
    android:layout_margin="4dp" 
    android:background="#FF0099FF" /> 

    <LinearLayout 
     android:paddingTop="4dp" 
     android:paddingRight="4dp" 
     android:paddingLeft="4dp" 
     android:paddingBottom="2dp"> 

     <TextView 
      android:id="@+id/title" 
      android:text="{title}" 
      android:textSize="@dimen/text_size_medium" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:layout_weight="10" 
      android:textStyle="bold" /> 

    </LinearLayout> 

活動其中I調用ViewBinder(類TextActivity延伸ListActivity

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

    String[] from = new String[]{ NoteAdapter.KEY_CATID, NoteAdapter.KEY_TITLE, NoteAdapter.KEY_CONTENT }; 
    int[] to = new int[]{ R.id.catcolor, R.id.title, R.id.content }; 

    SimpleCursorAdapter notes = new SimpleCursorAdapter(this, R.layout.noterow, notesCursor, from, to); 
    notes.setViewBinder(new ViewBinder()); 
    setListAdapter(notes); 
} 

private class ViewBinder implements SimpleCursorAdapter.ViewBinder { 
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) { 
     int viewId = view.getId(); 
     switch(viewId) { 
     case R.id.catcolor: 
      ImageView catcolor = (ImageView) view; 

      int catColor = cursor.getInt(columnIndex); 
      switch(catColor) { 
      case 0: 
       catcolor.setBackgroundColor(R.color.catcolor1); 
      break; 
      case 1: 
       catcolor.setBackgroundColor(R.color.catcolor2); 
      break; 
      case 2: 
       catcolor.setBackgroundColor(R.color.catcolor3); 
      break; 
      } 
     break; 
     } 
     return false; 
    } 
} 

我在做什麼錯?

回答

0

setViewValue()中,一旦設置了指定視圖所需的值,就必須返回true。查看documentation瞭解更多信息。以下是我正在考慮的代碼:

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

     int catColor = cursor.getInt(columnIndex); 
     switch(catColor) { 
     case 0: 
      catcolor.setBackgroundColor(R.color.catcolor1); 
      return true; 
     break; 
     case 1: 
      catcolor.setBackgroundColor(R.color.catcolor2); 
      return true; 
     break; 
     case 2: 
      catcolor.setBackgroundColor(R.color.catcolor3); 
      return true; 
     break; 
     } 
    break; 
    } 
    return false; 
} 
相關問題