Java – Position changes in recyclerview when scrolling

Position changes in recyclerview when scrolling… here is a solution to the problem.

Position changes in recyclerview when scrolling

The position in the recylerview seems to change as you scroll.

Here’s what I want to do

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 the visibility GONE of these icons as the default in the xml file.

When I first see the recylerview, the icons appear as expected based on their location.

However, when I scroll down and up, incorrect icons also appear in incorrect positions.
Just like otherIcon appears on the first and second items as you scroll down and up. As you scroll down, zeroIcon and oneIcon appear on some other items.

How do I fix this?

list_item.xml so

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

Solution

Modify it like this,

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 also manage other Views when you change items.

Related Problems and Solutions