【问题标题】:Android SimpleCursorAdapter - Adding conditional imagesAndroid SimpleCursorAdapter - 添加条件图像
【发布时间】:2011-09-16 02:44:11
【问题描述】:

所以我使用 SimpleCursorAdapter 将数据从 SQLite 适配到 ListView。让我们将此数据库称为 testData。我在 testData 中的一列记录了真或假,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}); 

【问题讨论】:

    标签: android simplecursoradapter


    【解决方案1】:

    我创建了一个自定义的 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
    

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

    【讨论】:

      猜你喜欢
      • 2013-04-14
      • 2011-10-06
      • 2020-11-23
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2014-09-28
      • 2012-10-31
      • 1970-01-01
      相关资源
      最近更新 更多