2010-11-29 38 views
0

我在更改列表视图中特定行的背景颜色时感到困惑,下面是我尝试的代码。当我滚动列表时,不同的行会突出显示,我想了解背后的原因。逻辑似乎很简单,但结果是不可预测的。我该怎么做到这一点。更改Android自定义ListView中特定行的背景色难度

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     if (convertView == null) { 
      convertView = mInflater.inflate(R.layout.rows_for_layout, null); 
      holder = new ViewHolder(); 
      holder.name = (TextView)convertView.findViewById(R.id.name); 
      holder.rated=(ImageView)convertView.findViewById(R.id.rated); 
       convertView.setTag(holder); 
      }else { 
       holder = (ViewHolder) convertView.getTag(); 
      } 

      //selected_position is the position where the list has to be highlighted 
      if(position==selected_position){ 
       holder.name.setText(elements.get(position).get("name")); 
      convertView.setBackgroundResource(R.drawable.highlight_this); 
      holder.rated.setBackgroundResource(R.drawable.star_image); 
      }else{ 
       holder.name.setText(elements.get(position).get("name")); 

      } 


     return convertView; 
    }//getView ![alt text][1] 
+0

看不出任何代码的问题,当你改变/更新“selected_position”变量? – 2010-11-29 10:38:00

+0

我在onCreate()方法中设置变量'selected_position'的值,以供参考,请查看此网址的完整代码http://pastebin.com/ki7q6Wy0 – ganesh 2010-11-29 11:19:20

回答

1

Your else语句不会将背景颜色重置为原来的颜色。 getView方法可以回收之前在列表中但不再可见的视图。如果背景被改变,那么它仍然是从最初创建时的背景颜色,这可能取决于你的状态。

所以,“重置”认为,添加以下你的东西:

if(position==selected_position){ 
      holder.name.setText(elements.get(position).get("name")); 
     convertView.setBackgroundResource(R.drawable.highlight_this); 
     holder.rated.setBackgroundResource(R.drawable.star_image); 
     }else{ 
      holder.name.setText(elements.get(position).get("name")); 
      //Add this 
      convertView.setBackgroundResource(R.drawable.not_highlighted); 
     } 
相关问题