【问题标题】:Android: change backgroundcolor of items in listviewAndroid:更改列表视图中项目的背景颜色
【发布时间】:2014-10-15 07:51:32
【问题描述】:

我想创建一个带有截止日期的笔记列表。如果到了截止日期,背景颜色应该会改变。

我尝试管理 ArrayAdapter 中的项目并将适配器绑定到 listview 活动的 listview。

我找到了 getChildCount() 和 getHeaderViewsCount() 方法,但都返回 0。

这是我试过的代码:

ListView lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mStringList));
for (int i = lv.getFirstVisiblePosition(); i < lv.getChildCount(); i++) {
            View v = lv.getChildAt(i);
            Log.d("MyActivity", String.valueOf(v.getId()));
            v.setBackgroundColor(Color.GREEN);
        }

由于 getFirstVisiblePosition 返回 0 并且 getChildCount 返回 0,因此永远不会进入循环。

这些是访问列表视图子元素的正确方法吗?

【问题讨论】:

  • 使用自定义listview适配器并在getView()方法中应用您的条件
  • 你必须为列表视图实现自定义适配器

标签: android listview android-listview


【解决方案1】:

您的背景颜色应在适配器的 getView 方法中设置为一种颜色或另一种颜色,您只需在适配器上调用 notifyDataSetChanged 即可请求刷新元素。

【讨论】:

    【解决方案2】:

    应该是“自定义ListView”,见here

    【讨论】:

      【解决方案3】:

      使用自定义适配器,然后在 getView 中您可以检查行内容并相应地调整颜色。

      这是一个很好的教程: http://webdeveloperpadawan.blogspot.co.uk/2014/09/android-listview-with-differing-rows.html

      【讨论】:

      • 很酷的教程!我根据 viewHolder Pattern 实现了自己的 ArrayAdapter。现在一切正常!
      【解决方案4】:

      试试这个

      v.setBackgroundResource(R.Color.GREEN);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-01-15
        • 2016-07-17
        • 1970-01-01
        • 2012-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多