-1

I am using a RecyclerView to show list of products in my app, I need to group the product based on aisle. while the data are fetched for the first time in the list, the products are grouped correctly with respect to aisle. When we scroll the view, the aisle group divider is shown for the wrong item and the divider gets restored to correct position once the onBindViewHolder gets refreshed automatically.

MyAdapter.class
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) { 
    itemsGrouping(pickItem, pickItemView, holder.adapterPosition)
}

private fun itemsGrouping(pickItem: PickItem, pickItemView: View, adapterPosition: Int) {
//Based on some condition
if(SomeCondition)
    itemDivider(pickItemView,true)
else 
    itemDivider(pickItemView,false)
}

private fun itemDivider(v: View, boolean: Boolean) {
    if(boolean) {
        v.visibility = View.VISIBLE
    } else {
        v.visibility = View.GONE
    }
 }
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433

2 Answers2

0

Well, you should know that the view holders are reused in the RecyclerView, so it's probable not the right idea to try to determine the visibility of the divider in onBindViewHolder. I would recommend using item decorator for dividers. Here's the question and answer for that How to add dividers and spaces between items in RecyclerView?

RexSplode
  • 1,475
  • 1
  • 16
  • 24
0

The problem is RecyclerView recycles previous views in order to be efficient. I guess "SomeCondition" contains artifacts which are from previous holders.

So at

itemsGrouping(pickItem, pickItemView, holder.adapterPosition)

you should get pickItem and pickItemView from newly bound holder. You should use like

pickItemView = holder.findViewById(R.id.pickItemView);

Or consider using DataBinding Library

Here is a good example (it's in Kotlin) : DataBoundListAdapter

Once you extend your adapter to DataBoundListAdapter and override bind() method, everything inside bind is executed for every row, so you won't get repeated results.

Note : notice "executePendingBindings()"

Ali Korkmaz
  • 324
  • 2
  • 4