将图像添加到ListView

时间:2012-03-28 20:17:37

标签: java android database sqlite

我有一个从sqlite数据库填充的listview并且工作正常,但我希望在文本旁边填写一张图片。

所以目前ListView会显示字符名称。我希望得到另一个字段,如果该字段等于x set picture x else,如果该字段等于y显示图片y。

我可以使用当前的实现添加图像吗?

listContent = (ListView) findViewById(R.id.contentlist);
mDbAdapter = new DbAdapter(this);
mDbAdapter.open();
Cursor cursor = mDbAdapter.fetchAll();
startManagingCursor(cursor);
String[] from = new String[] { DbAdapter.KEY_NAME };
int[] to = new int[] { R.id.text };
cursorAdapter = new SimpleCursorAdapter(this, R.layout.row, cursor, from, to);
listContent.setAdapter(cursorAdapter);
mDbAdapter.close();

继承人xml

<ImageView
    android:id="@+id/icon"
    android:layout_gravity="left"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:padding="5dp" />

<TextView
    android:id="@+id/text"
    android:text="Name"
    android:paddingLeft="10dip"
    android:layout_weight="0.5"
    android:layout_gravity="center"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="30dp"
    android:padding="5dp" />
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

SimpleCursorAdapter的文档中,您无法使用该构造函数中的from和to方法将图像绑定到视图。但是,您可以通过扩展SimpleCursorAdapter并覆盖getViewBinder()来返回自己的ViewBinder,轻松完成您要执行的操作。您的ViewBinder应处理读取当前行并将文本绑定到视图以及图像。