Adjust library sublist scroll on changes

This commit is contained in:
Koitharu
2022-07-22 14:41:34 +03:00
parent 7c659371a9
commit e6202103bc
2 changed files with 32 additions and 0 deletions

View File

@@ -48,6 +48,7 @@ fun libraryGroupAD(
MangaItemDiffCallback(),
mangaGridItemAD(coil, lifecycleOwner, listenerAdapter, sizeResolver),
)
adapter.registerAdapterDataObserver(ScrollKeepObserver(binding.recyclerView))
binding.recyclerView.setRecycledViewPool(sharedPool)
binding.recyclerView.adapter = adapter
val spacingDecoration = SpacingItemDecoration(context.resources.getDimensionPixelOffset(R.dimen.grid_spacing))

View File

@@ -0,0 +1,31 @@
package org.koitharu.kotatsu.library.ui.adapter
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class ScrollKeepObserver(
private val recyclerView: RecyclerView,
) : RecyclerView.AdapterDataObserver() {
private val layoutManager: LinearLayoutManager
get() = recyclerView.layoutManager as LinearLayoutManager
override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) {
val position = minOf(toPosition, fromPosition) // if items are swapping positions may be swapped too
if (position < layoutManager.findFirstVisibleItemPosition()) {
postScroll(position)
}
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
if (positionStart < layoutManager.findFirstVisibleItemPosition()) {
postScroll(positionStart)
}
}
private fun postScroll(targetPosition: Int) {
recyclerView.post {
layoutManager.scrollToPositionWithOffset(targetPosition, 0)
}
}
}