【问题标题】:Difficulty in changing the background color of a particular row in an Android Custom ListView难以更改 Android 自定义 ListView 中特定行的背景颜色
【发布时间】:2011-05-17 04:59:21
【问题描述】:

我对更改列表视图中特定行的背景颜色感到困惑,下面是我尝试过的代码。当我滚动列表时,不同的行会突出显示,我想了解这背后的原因。逻辑似乎很简单,但结果却是不可预测的。我应该如何实现这一目标。

 @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]

【问题讨论】:

  • 没有发现代码有任何问题,您何时更改/更新“selected_position”变量?
  • 我在 onCreate() 方法中设置变量 'selected_position' 的值,作为参考,请查看此 url 以获取完整代码pastebin.com/ki7q6Wy0
  • 您可以在i56.tinypic.com/10x7rsw.png查看图片

标签: android listview colors background


【解决方案1】:

您的 else 语句不会将背景颜色重置为其原始颜色。 getView 方法可以回收以前在列表中但不再可见的视图。如果背景发生了变化,那么它仍然是最初创建时的背景颜色,这取决于您的状态。

因此,要“重置”它,请在 else 中添加以下内容:

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);
         }

【讨论】:

  • 但是,你为什么要那样工作?相反,我会使用选择器作为背景,选择/未选择/...状态?它比当前的方法干净得多。
  • 感谢 eMich 的回复,但我已经有一个列表视图选择器,并且按照您所说的完成,除此之外,我只需要突出显示列表中的一个特定行即可这个很特别。我已经恢复为特殊行使用“R.drawable.highlight_this”,其余部分使用透明可绘制对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 1970-01-01
相关资源
最近更新 更多