2014-01-26 37 views
0

我从.txt文件中读取值,并使用ArrayAdapter将它们放入GridView中,并且它可以很好地工作。 但是我想根据物品的价值改变物品的颜色。在GridView中获取不同的项目

例如: 1是灰色 2红 3是蓝 4 ...

但我不能在GridView改变单一项目的backgroundColor,只能是整个GV。

GridView gv = (GridView) findViewById(R.id.gvSpeelveld); 
gv.setBackgroundColor(Color.GREEN); 

这个尝试是不成功的

//View is null 
View v = gv.getChildAt(2); 
v.setBackgroundColor(Color.CYAN); 

但我怎么能得到一个单一的GridView的不同的项目吗? for循环将非常有用。

View app

+0

你必须将背景设置为个别项目在适配器的'getView()'方法... –

回答

0

在你的适配器的getView(int position, View view, ViewGroup parent)方法,获得该项目的值在给定的位置(使用位置PARAM)。然后使用类似switch-case的东西并为该网格项设置backgroundcolor。

就是这样。

//说你在getView方法获得该项目的价值...

switch(value){ 

case 1: 
    view.setBackgroundColor(Color.GRAY); //grey 
    break; 
case 2: 
    view.setBackgroundColor(Color.RED); //red 
    break; 
} 

//so on