Android SimpleCursorAdapter - 添加条件图像

2023-11-29

因此,我使用 SimpleCursorAdapter 将数据从 SQLite 调整到 ListView 中。我们将此数据库称为 testData。我在 testData 中的一列记录 true 或 false,值为 0 或 1。我可以让列表视图根据该行是否有 0 或 1 为每个项目显示不同的图像吗?

这是我正在使用的适配器。

ListAdapter adapter = new SimpleCursorAdapter(
this, 
android.R.layout.two_line_list_item,  
mCursor,                                              
new String[] {testData.DATE1, testData.NAME1},           
new int[] {android.R.id.text1, android.R.id.text2}); 

我创建了一个自定义的 SimpleCursorAdapter:

public class MySimpleCursorAdapter extends SimpleCursorAdapter {

    public MySimpleCursorAdapter(Context context, int layout, Cursor cur,
             String[] from, int[] to) {
        super(context, layout, cur, from, to);
    }

    @Override public void setViewImage(ImageView iv, String text)
    {
        if (text.equals("0")) {
            iv.setImageResource(R.drawable.new1);
        }
        else {
            iv.setImageResource(R.drawable.check1);
        }
    }

}

在我的 ListActivity 中,我将数据库中的文本字段绑定到图像资源 id。在你的例子中它看起来像这样:

ListAdapter adapter = new MySimpleCursorAdapter(
    this, 
    android.R.layout.two_line_list_item,  
    mCursor,                                              
    new String[] {testData.DATE1, testData.NAME1},           
    new int[] {android.R.id.text1, android.R.id.image1}); // Note: replace text2 with image1

IE。如果数据库中的文本字段“Name1”包含“0”,则图像“new1”将显示在ListView中,如果它有其他值,则将显示“check1”。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android SimpleCursorAdapter - 添加条件图像 的相关文章

随机推荐