开发者

Difficulty in changing the background color of a particular row in an Android Custom ListView

I am confused in changing the background colour of a particular row in an list view, below is the code I tried. Different rows gets highlighted as i scroll the list, I could like to understand the reason behind this. The logic seems to quite simple, but the results are unpredictable. How am I supposed to achieve this.

 @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();
       开发者_如何学Python     } 

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


Your else statement does not reset the background color to its original. The getView method can recycle a view that was previously in your list but is not visible anymore. If the background was changed, then it will still be that background color from when it was originally created, which can depend on your state.

So, to "reset" that, add the following in your 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);
         }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜