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

10

我是Android开发的新手(两天前开始),已经学习了一些教程。我正在使用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);
}

我的布局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"/>

我真的不知道如何根据所选笔记类型获取正确的可绘制对象。目前,我可以从Spinner中选择类型,因此在数据库中存储的是整数。我创建了一些与这些整数对应的图像,但似乎没有起作用。

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

1个回答

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());

非常棒 - 完美运作。没有比这更简单的解决方案了 :). 您有我的真诚感谢! - Butteredchops
我想补充一点,你不需要在setViewValue中覆盖所有情况,只需要针对ImageView进行处理。对于其他所有视图,你应该返回false,这样Android就会应用你提供给SimpleCursorAdapter的正常绑定。 - Konstantin Milyutin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接