At First, my RecyclerView items are ok, but on scrolling, items are shown on the wrong position for example: item 6 shown in position 67. Although onClick listener and getAdapte
In your adapter class override this method and replace position to getItemViewType(position)
@Override
public int getItemViewType(int position) {
return position;
}
in
public void onBindViewHolder()
add
holder.setIsRecyclable(false);
None of the methods above worked in every situation for me and I don't want to sacrifice the recyclability. The only working solution that I found is to modify the return for both of these methods inside the adapter to "position" values:
override fun getItemViewType(position: Int): Int {
return position
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
The returned position will be always correct. It needs to be modified if you are using viewType.
In my case this problem was happening because I had setHasStableIds(true)
in one RecyclerView.Adapter
(in fact, it was HasStableIds = true;
since I work in Xamarin.Android).
After removing that line (HasStableIds
is false
by default), all positions got back to normal and I didn't need to disable recycling or to return position
from GetItemViewType(int position)
(which is nice because I actually use this method to choose between multiple ViewHolder
types). Then just out of interest I tried to enable HasStableIds
and override long GetItemId(int position)
– it also worked well.
So my conclusion is: if for some reason you need to enable HasStableIds
, you should override both long GetItemId(int position)
and int GetItemViewType(int position)
in your RecyclerView.Adapter
's subclass. If you do not have unique item IDs and/or different view types, just returning back the position
parameter will do the job.