Android:根据数据库字段数据更改ImageView src

But*_*ops 10 android

我对Android开发很新(2天前开始)并且已经通过了许多教程.我正在Android SDK中的NotePad练习(链接到教程)中构建测试应用程序,并作为笔记列表的一部分,我想显示不同的图像,具体取决于我称为"notetype"的数据库字段的内容.我想在每个记事本条目之前将此图像显示在列表视图中.

我的.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);
}
Run Code Online (Sandbox Code Playgroud)

我的布局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"/>
Run Code Online (Sandbox Code Playgroud)

我真的不知道如何根据所选音符的类型来获取正确的画面.目前我能够从Spinner中选择类型,因此存储在数据库中的是一个整数.我已经创建了一些与这些整数相对应的图像,但它似乎没有提到.

任何帮助,将不胜感激.如果您需要更多信息,请告诉我.

m6t*_*6tt 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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

}

然后将其添加到适配器

note.setViewBinder(new MyViewBinder());
Run Code Online (Sandbox Code Playgroud)