RecyclerView.Adapter中的ViewHolder并非特定于位置

时间:2014-09-27 16:03:51

标签: android android-5.0-lollipop android-recyclerview android-viewholder

以下是我的onBindViewHolder代码(内部MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>

的一部分
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // - get element from your dataset at this position
    StatusItem item = mDataset.get(position);
    //......
    //Add content and timing to the textview
    String content = item.getContent();

    holder.mTextViewTime.setText(timing);
    //Set the img
    holder.imgViewIcon.setImageDrawable(item.getProfileDrawable());
    //Set content image (for Instagram)
    holder.mImageViewContentPic.setImageDrawable(item.getContentDrawable());
    //HIDE THE VIEW Start
    if(item.getContentDrawable() == null){
        holder.mImageViewContentPic.setVisibility(View.GONE);
    }
    //HIDE THE VIEW End
}

部分HIDE THE VIEW未按预期工作。 当我向下滚动时,视图正常工作。但是,当我开始向上滚动,即重新访问先前的视图时,应该是VISIBLE的ImageView变为GONE,尽管我检查了我的数据集并验证它没有被修改。尝试在视图上调用其他方法也会产生不稳定的结果(数据集中的位置和项目不匹配)。

似乎视图持有者没有绑定到RecyclerView内的特定位置。

如果删除HIDE THE VIEW部分,代码将按预期工作。 有没有办法解决这个问题,并在我的情况下动态隐藏视图?

注意:我使用了一些AsyncTasks来更新数据集并调用notifyDataSetChanged(),如果这是相关的。

2 个答案:

答案 0 :(得分:8)

###This is the solution to your problem:###

holder.mImageViewContentPic.setVisibility(View.VISIBLE);
if(item.getContentDrawable() == null){
        holder.mImageViewContentPic.setVisibility(View.GONE);
    }

答案 1 :(得分:0)

由于RecyclerView非常好地使用了回收,ViewHolder A可能会被用作ViewHolder B,因此您需要具体ViewHolder的所有属性属性附加到错误的对象。

相关问题