【问题标题】:Android : Change the background color of a listview/gridviewAndroid:更改列表视图/网格视图的背景颜色
【发布时间】:2016-07-17 11:39:36
【问题描述】:

我正在尝试更改网格视图中所选项目的背景,所以我使用以下代码来做到这一点

gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

                    // Basically changes the boolean value of an object's variable to "true", this means it has been clicked on 
                    Themes.themes.get((int)id).clicked= true;

                    // Reload the list 
                    adapter.notifyDataSetChanged();
                    }
                });

然后在我使用的适配器类的getview() 方法中

if(theme.clicked)
            convertView.setBackgroundColor(context.getResources().getColor(android.R.color.holo_green_dark));

一旦我点击我的 gridview 的一个项目,它的背景颜色就会改变,但是当我向下滚动时,gridview 中其他单元格的背景颜色也会改变。我厌倦了使用不同的方法来应用 onclick 事件(例如使用选择器),但似乎没有任何效果。

有人知道解决这个问题的方法吗? 提前致谢!

【问题讨论】:

  • 一种方法是将颜色属性放在适配器中然后检索它,您的视图正在回收,这就是它发生的原因
  • @lawonga 正如您所说,视图的回收确实是问题的根源。但是 color 属性实际上是在适配器中处理的,我的代码检查对象的“clicked”属性,如果它是真的,它会将要返回的视图着色为绿色,否则什么也不会发生。
  • 嗯。也是arraylist中项目的属性吗?如果是这样,它不应该搞砸。
  • @lawonga 该属性在arraylist的每个对象中。所以是的,它不应该搞砸,但我找到了解决方案。谢谢!

标签: android listview gridview background-color


【解决方案1】:

这个问题是因为视图的回收。您还需要为未选中的项目设置背景颜色。

if(theme.clicked)
            convertView.setBackgroundColor(context.getResources().getColor(android.R.color.holo_green_dark));

else {
       //Set the default color here for unselected items
}

【讨论】:

  • 很奇怪,这解决了我的问题,这是我永远不会想到的!非常感谢!
【解决方案2】:

假设您在可绘制文件夹名称中有一个背景 selector_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/colorPrimaryPress"/>
    <item android:drawable="@color/colorPrimary" />
</selector>

我假设您的 gridView 的单元格有一个布局? 如果是这样设置 android:background="@drawable/selector_bg"

【讨论】:

  • 感谢您的帮助。实际上我已经尝试过这种方式,但它没有用,我只是再次尝试但仍然没有。一旦我单击,单元格的颜色会发生什么变化,一旦释放单击,单元格的颜色就会恢复到最初的样子。
猜你喜欢
  • 1970-01-01
  • 2012-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多