简体   繁体   中英

ViewHolder in RecyclerView.Adapter not specific to position

The following is part of my code for onBindViewHolder (inside 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
}

The part HIDE THE VIEW is not working as expected. When I am scrolling downwards, the views are working normally. However, when I start to scroll upwards, ie revisited the previous views, the ImageViews that are supposed to be VISIBLE becomes GONE , although I checked my dataset and verified that it has not been modified. Try calling other methods on the views also give erratic results(positions and items in dataset do not match).

It seems that the view holders are not binded to specific positions inside the RecyclerView.

The code works as expected if I remove the HIDE THE VIEW part. Is there any way to solve this issue and dynamically hide views in my case?

Note: I used some AsyncTasks to update the dataset and call notifyDataSetChanged() , if that is relevant.

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

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

由于RecyclerView非常好地使用了回收, ViewHolder A可能会被用作ViewHolder B,因此如果某些属性附加到错误的对象,则需要特定ViewHolder每个属性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM