Created
November 29, 2023 04:32
-
-
Save hoangchungk53qx1/7816666adba73bdba856e52646b9aeb9 to your computer and use it in GitHub Desktop.
This observer detects when item was added or moved to the first position of the adapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * This observer detects when item was added or moved to the first position of the adapter, while recyclerView is scrolled to the top. This is necessary | |
| * to force recycler to scroll to the top to make such item visible, because by default it will keep items on screen, while adding new item to the top, | |
| * outside of the viewport | |
| * @param layoutManager - [LinearLayoutManager] of the recycler view, which displays items | |
| * @property onItemUpdated - callback to be called, when observer detects event | |
| */ | |
| class FirstItemUpdatedObserver( | |
| layoutManager: LinearLayoutManager, | |
| private val onItemUpdated: () -> Unit | |
| ) : RecyclerView.AdapterDataObserver() { | |
| val layoutManager: LinearLayoutManager? by weak(layoutManager) | |
| override fun onItemRangeMoved(fromPosition: Int, toPosition: Int, itemCount: Int) { | |
| if ((toPosition == 0 || fromPosition == 0) && layoutManager?.findFirstCompletelyVisibleItemPosition() == 0) { | |
| onItemUpdated.invoke() | |
| } | |
| } | |
| override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { | |
| if (positionStart == 0 && layoutManager?.findFirstCompletelyVisibleItemPosition() == 0) { | |
| onItemUpdated.invoke() | |
| } | |
| } | |
| } | |
| // Usetag | |
| private lateinit var roomListPagerAdapter: RoomListPagingAdapter | |
| roomListPagerAdapter.registerAdapterDataObserver(firstItemObserver) | |
| roomListPagerAdapter.unregisterAdapterDataObserver(firstItemObserver) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment