Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/192.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android:更改listview/gridview的背景色_Android_Listview_Gridview_Background Color - Fatal编程技术网

Android:更改listview/gridview的背景色

Android:更改listview/gridview的背景色,android,listview,gridview,background-color,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

我试图在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();
                    }
                });
单击gridview中的某个项目后,其背景颜色会发生变化,但向下滚动时,gridview中其他单元格的背景颜色也会发生变化。我厌倦了使用不同的方法来应用onclick事件,就像使用选择器一样,但似乎没有任何效果

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

假设您在可绘制文件夹名称选择器_bg.xml中有背景

我想你有gridView单元的布局吗?
如果这样设置android:background=@drawable/selector_bg

这个问题是因为视图的循环使用。您还需要为未选中的项目设置背景色

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

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

一种方法是将color属性放在适配器中,然后检索它,您的视图正在循环使用,因此happening@lawonga正如你所说,观点的循环利用确实是问题的根源。但是颜色属性实际上是在适配器中处理的,我的代码会检查对象的clicked属性,如果它是真的,它会将要返回的视图涂成绿色,否则什么也不会发生。Hm。项目中的属性是否也在arraylist中?如果是这样的话,它就不会出错。@lawonga属性位于arraylist的每个对象中。所以是的,它不应该搞砸,但我已经找到了解决办法。谢谢谢谢你的帮助。事实上,我已经尝试过这种方法,但它不起作用,我只是尝试了一次,但仍然没有任何效果。一旦我点击,细胞的颜色就会改变,一旦点击被释放,细胞的颜色就会恢复到最初的状态。奇怪的是,这解决了我的问题,我永远不会明白这一点!谢谢!
<?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>
if(theme.clicked)
            convertView.setBackgroundColor(context.getResources().getColor(android.R.color.holo_green_dark));

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