I have a ViewPager2 which is set to swipe horizontally. I idea is to build an infinite scrolling pager. The class looks something like this:
class SwipeAdapter(fragmentActivity: FragmentActivity): FragmentStateAdapter(fragmentActivity)
I have overridden the usual createFragment(position: Int): Fragment
where I am returning a new Fragment
I have a list of Ids that I am operating on which is the adapter data set.
private var contentIds = mutableListOf<Int>()
I have also implemented
override fun containsItem(itemId: Long): Boolean {
return contentIds.contains(itemId.toInt())
}
override fun getItemId(position: Int): Long {
return contentIds[position].toLong()
}
My DiffUtil looks like this:
inner class ContentIdsDiffCallback(private val oldItems: List<Int>, private val newItems: List<Int>) : DiffUtil.Callback() {
override fun getOldListSize(): Int {
return oldItems.size
}
override fun getNewListSize(): Int {
return newItems.size
}
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldItems[oldItemPosition] == newItems[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return areItemsTheSame(oldItemPosition, newItemPosition)
}
}
Nothing fancy happening here since I am dealing with Ids only.
How I am setting the data?
fun setData(data: MutableList<Int>) {
val diffCallback = ContentIdsDiffCallback(contentIds, data)
val diffResult = DiffUtil.calculateDiff(diffCallback, true)
contentIds.addAll(data)
diffResult.dispatchUpdatesTo(this)
}
So the logic is, I have registered a `registerOnPageChangeCallback` and overridden the method `onPageSelected`.
Over there, I check how many pages has the user swiped and when the user has swiped 60% of the items (val sixtyPercentItems: Int = ceil(viewpager2Adapter.itemCount - 1 * 0.6).toInt()
)
I call my API to fetch the next set of items.
When that APi returns, I call adapter.setData
(the method shown above).
**Surprisingly when that happens, my adapter resets to zero!** My list is not resetting i,e., it is *adding* the items, I haven't kept any special variable which would influence this behaviour. I am kind of in a fix. That was the whole point of DiffUtil right? Has anybody faced this?