【问题标题】:Populating single ListView with different row layouts使用不同的行布局填充单个 ListView
【发布时间】:2011-05-05 20:05:07
【问题描述】:

我正在尝试使用数据库中的列填充 ListView。我可以成功实现这一点,但问题是我想根据 id 是否与 PendingIntent 匹配来使用不同的布局资源。

这是为了检查是否存在带有 rowid 的警报,并且我计划在列表视图中提供视觉反馈,以向用户显示存在哪些警报。我可以根据 PendingIntents 成功检查 rowid 并获得返回布尔值。

我遇到的问题是使用不同行的不同布局资源填充 ListView(这甚至可能吗?),我不知道从哪里开始。

我目前有以下代码:

for(int x = 0; x < numNotes; x++)   {

            if(existAlarm(intarray[x])){
                String[] from = new String[] { TodoDbAdapter.KEY_SUMMARY };
                int[] to = new int[] { R.id.label1};
                cursor = dbHelper.fetchTodo(intarray[x]);

                SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
                        R.layout.todo_row_green, cursor, from, to);
                setListAdapter(notes); 

            } else if (!existAlarm(intarray[x])){

                String[] from = new String[] { TodoDbAdapter.KEY_SUMMARY };
                int[] to = new int[] { R.id.label};
                cursor = dbHelper.fetchTodo(intarray[x]);

                SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
                        R.layout.todo_row, cursor, from, to);
                setListAdapter(notes); 
            }   

        }

但 ListView 只显示循环中的最终数据库条目。

我将非常感谢任何指导,谢谢。

【问题讨论】:

    标签: java android sqlite android-listview


    【解决方案1】:

    当然,只会显示最后一项。这是因为您每次进入循环并执行时都会不断更改列表适配器。摆脱循环。

    如果我理解正确,您希望根据 ToDo 显示或不显示绿色行。如果是这样,请编写您自己的列表适配器,它是 SimpleCursorAdapter 的子类。然后覆盖newView (Context context, Cursor cursor, ViewGroup parent) 方法以选择用于显示行的视图。 cursor 参数已移动到正确的位置,因此您可以从数据库中检索值以进行任何必要的比较。

    例如:我假设(由于 fetchTodo(intarray[x]))您正在根据 ToDo 的 id 进行比较。在这种情况下,您的代码可能如下所示:

     public View newView (Context context, Cursor cursor, ViewGroup parent){
          long id = cursor.getLong(TodoDbAdapter.ROW_ID_COLUMN);
          LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
          if (existAlarm(id)){
               return inflater.inflate(R.layout.todo_row_green, null);
          } else {
               return inflater.inflate(R.layout.todo_row, null);
          }
     }
    

    我不知道我是否理解您的代码,但您可以根据自己的需要进行调整。

    【讨论】:

      【解决方案2】:

      很可能在每一行中使用不同的视图:但是你不能使用标准的 SimpleCursorAdapter:你必须重载 getView() 函数。一个例子是Trying to override getView in a SimpleCursorAdapter gives NullPointerExceptio (帖子中回答了几个错误,但基本技术是正确的)。

      就仅显示最后一篇文章而言,您的代码正在为每一行创建一个新的 SimpleCursorAdapter,这是不正确的。您想使用 getView() 覆盖,然后在其中进行 for 循环和比较。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多