Android:更改listview / gridview的背景颜色

时间:2016-03-29 18:33:45

标签: android listview gridview background-color

我试图更改gridview中所选项目的背景,因此我使用以下代码执行此操作

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事件(比如使用选择器),但似乎没有任何工作。

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

2 个答案:

答案 0 :(得分:2)

此问题是由于视图的回收。您还需要为未选择的项目设置背景颜色。

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

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

答案 1 :(得分:0)

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

None

我认为你有一个gridView的cellule布局? 如果是这样设置android:background =“@ drawable / selector_bg”

相关问题