2011-02-11 71 views
1

我有一个GridView,其中每个单元格包含一个ImageView和TextView。当用户单击一个单元格时,它将该单元格的背景颜色更改为灰色。但是,当我向下滚动时,也会选择另一个单元(即背景颜色为灰色)。当在GridView/ListView中选择一个单元格时,它也会选择另一个单元格

我的猜测是,这是因为单元格重用与滚动时隐藏的单元格相同的视图。

当我更改方向时也会发生这种情况。如果我选择单元格1,当我改变方向时,现在选择另一个单元格,而单元格1不是。

在此先感谢。

public class LazyFeaturedTopicItemAdapter extends BaseAdapter { 

private Activity activity; 
private ArrayList<Topic> topics; 
private static LayoutInflater inflater=null; 
public PostItemImageLoader imageLoader; 

public LazyFeaturedTopicItemAdapter(Activity a, ArrayList<Topic> d) { 
    activity = a; 
    topics=d; 
    inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    imageLoader=new PostItemImageLoader(activity.getApplicationContext()); 
} 

public int getCount() { 
    return topics.size(); 
} 

public Object getItem(int position) { 
    return position; 
} 

public long getItemId(int position) { 
    return position; 
} 

public static class ViewHolder{ 
    public ImageView imgThumbnail; 
    public TextView txtName; 
} 

public View getView(int position, View convertView, ViewGroup parent) { 
    View vi=convertView; 
    ViewHolder holder; 

    final Topic topicItem = topics.get(position); 

    if(convertView==null){ 
     vi = inflater.inflate(R.layout.featured_topic_item, null); 
     holder=new ViewHolder(); 
     holder.txtName = (TextView) vi.findViewById(R.id.featured_topic_item_name); 
     holder.imgThumbnail = (ImageView)vi.findViewById(R.id.featured_topic_item_thumbnail); 

     vi.setTag(holder); 
    } 
    else 
     holder=(ViewHolder)vi.getTag(); 
     holder.txtName.setText(topicItem.getName());          

    holder.imgThumbnail.setTag(topicItem.getPictureLink()); 
    imageLoader.DisplayImage(topicItem.getPictureLink(), activity, holder.imgThumbnail); 

    vi.setOnClickListener(
      new View.OnClickListener() { 

       @Override 
       public void onClick(final View v) { 

        if (topicItem.isSelected) { 
         v.setBackgroundColor(Color.WHITE); 
         topicItem.isSelected = false; 
        } 
        else { 
         v.setBackgroundColor(Color.GRAY); 
         topicItem.isSelected = true; 
        } 
       } 

      } 
    ); 
    return vi; 
} 
} 

这是解决方案,以防有人感兴趣。我在侦听器之前添加了以下代码。

if (topicItem.isSelected) { 
     vi.setBackgroundColor(Color.GRAY); 
    } 
    else { 
     vi.setBackgroundColor(Color.WHITE); 
    } 

回答

1

你是对你的猜测,认为是被重用 为了解决这个问题,你可以只设置在监听前加

vi.setBackgroundColor(Color.WHITE); 
topicItem.isSelected = false; 

,把它看成是“默认”行为

我希望可以帮助

+0

很好的答案! 我刚刚更新了上面的问题。非常感谢你。 – dannyroa 2011-02-11 21:22:59

相关问题