【问题标题】:Android: Changing an ImageView src depending on database field dataAndroid:根据数据库字段数据更改 ImageView src
【发布时间】:2010-05-05 21:19:24
【问题描述】:

我对 Android 开发很陌生(两天前开始),并且已经学习了许多教程。我正在从 Android SDK 中的 NotePad 练习 (Link to tutorial) 构建一个测试应用程序,作为笔记列表的一部分,我想根据我称为“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 中选择类型,所以存储在数据库中的是一个整数。我已经创建了一些与这些整数相对应的图像,但它似乎无法识别。

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

【问题讨论】:

    标签: android


    【解决方案1】:

    您可能想尝试使用 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());
    

    【讨论】:

    • 优秀 - 完美运行。不能要求更简单的解决方案:)。我衷心感谢您!
    • 我想补充一点,您不必涵盖setViewValue 中的所有案例,仅针对ImageView。对于所有其他视图,您应该只返回false,在这种情况下,Android 将应用您提供给 SimpleCursorAdapter 的普通绑定。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-29
    • 2017-12-27
    • 1970-01-01
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 2019-12-01
    相关资源
    最近更新 更多