Ad

Position In Recylerview Changes While Scrolling

- 1 answer

Seems like position in recylerview changes while scrolling.

What I want to do is like this.

Adapter.java

@Override
public void onBindViewHolder(aViewHolder holder, int position) {

    if (position == 0) {
        holder.zeroIcon.setVisibility(View.VISIBLE);
    } else if (position == 1) {
        holder.oneIcon.setVisiblity(View.VISIBLE);
    } else {
        holder.otherIcon.setVisiblity(View.VISIBLE);
    }

    // Set text on each item
    ...
}


@Override
public int getItemCount() { return models.size(); }

public class aViewHolder extends RecyclerView.ViewHolder {

    private ImageView zeroIcon;
    private ImageView oneIcon;
    private ImageView otherIcon;


    public aViewHolder(View itemView) {
        super(itemView);
        zeroIcon = itemview.findViewById(...);
        ...
    }
}

I set these icon's visibility GONE as default in xml file.

When I see the recylerview at first, the icons show up as I expected depending on its position.

However, when I scroll down and scroll up, incorrect icons also show up on incorrect position. Like otherIcon shows up on the first and second item while scrolling down and up. While scrolling down, zeroIcon and oneIcon show up on some other items.

How can I fix this?

list_item.xml is like this.

<RelativeLayout ...>

     <ImageView
         android:id="@+id/zero"
         android:visiblity="gone"
         android:background="@drawable/zero" />

     <ImageView
         android:id="@id/one"
         android:visiblity="gone"
         android:background="@drawable/one" />

     <ImageView
         android:id="@id/other"
         android:visiblity="gone"
         android:background="@drawable/other" />
Ad

Answer

Modify it in this way,

if (position == 0) {
    holder.zeroIcon.setVisibility(View.VISIBLE);
    holder.otherIcon.setVisiblity(View.GONE);
    holder.oneIcon.setVisiblity(View.GONE);
} else if (position == 1) {
    holder.oneIcon.setVisiblity(View.VISIBLE);
    holder.zeroIcon.setVisibility(View.GONE);
    holder.otherIcon.setVisiblity(View.GONE);
} else {
    holder.otherIcon.setVisiblity(View.VISIBLE);
    holder.oneIcon.setVisiblity(View.GONE);
    holder.zeroIcon.setVisibility(View.GONE);
}

In RecyclerView you should manage other views also while changing an item.

Ad
source: stackoverflow.com
Ad