问题
I'm trying to add a background color for an TextView
on my ListView
using a SimpleCursorAdapter
with ViewBinder
, but it doesn't work:
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>
Activity where I call the ViewBinder
(class TextActivity
extends 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;
}
}
What am I doing wrong?
回答1:
In setViewValue()
, you have to return true once you've set the value wanted for the specified view. Check out the documentation for more info. Here's what I'm thinking of for your code:
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;
}
来源:https://stackoverflow.com/questions/7628824/using-viewbinder-for-a-custom-listview-item-with-textview