RecyclerView wrong position set onBindViewHolder

前端 未结 4 1299
误落风尘
误落风尘 2021-02-18 13:30

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

相关标签:
4条回答
  • In your adapter class override this method and replace position to getItemViewType(position)

    @Override
    public int getItemViewType(int position) {
        return position;
    }
    
    0 讨论(0)
  • 2021-02-18 13:54

    in public void onBindViewHolder()

    add

    holder.setIsRecyclable(false);
    
    0 讨论(0)
  • 2021-02-18 13:59

    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.

    0 讨论(0)
  • 2021-02-18 13:59

    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.

    0 讨论(0)
提交回复
热议问题