I'm quite new to Android development (started 2 days ago) and have been through a number of tutorials already. I'm building a test app from the NotePad exercise (Link to tutorial) in the Android SDK and as part of the list of notes I want to display a different image depending on the contents of a database field i've called "notetype". I'd like this image to appear in the List view before each notepad entry.
The code in my .java file is:
private void fillData() {
Cursor notesCursor = mDbHelper.fetchAllNotes();
notesCursor = mDbHelper.fetchAllNotes();
startManagingCursor(notesCursor);
String[] from = new String[]{NotesDbAdapter.KEY_NOTENAME, NotesDbAdapter.KEY_NOTETYPE};
int开发者_C百科[] 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);
}
And my layout xml file (notes_row.xml) looks like this:
<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"/>
I just really have no clue how I'd go about fetching the right drawable depending on the type of note that has been selected. At the moment I have the ability to select the type from a Spinner, so what gets stored in the database is an integer. I've created some images that correspond to these integers but it doesn't seem to pick things up.
Any help would be appreciated. If you need more info then please let me know.
You might want to try using a ViewBinder. http://d.android.com/reference/android/widget/SimpleCursorAdapter.ViewBinder.html
This example should help:
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;
}
}
}
Then add it to your adapter with
note.setViewBinder(new MyViewBinder());
精彩评论