How to correctly scroll after item inserted into PagedListAdapter
Asked Answered
S

1

18

I am using the Android Arch PagedListAdapter class. The issue I have run into is that since my app is a chat style app, I need to scroll to position 0 when an item is inserted. But the PagedListAdapter finds the diffs and calls necessary methods on the background thread so it seems that there is no dependable way to call layoutManager.scrollToPosition(0)

If anyone has any ideas on how I could scroll at the right time, it would be greatly appreciated. Thanks!

Here is my Room Dao:

@Dao
abstract class MessagesDao {

    @Query("SELECT ...")
    abstract fun getConversation(threadId: String): DataSource.Factory<Int, Conversation>

}

and then the LivePagedListBuilder:

LivePagedListBuilder(database.messagesDao.getConversation(threadId), PagedList.Config.Builder()
            .setInitialLoadSizeHint(20)
            .setPageSize(12)
            .setEnablePlaceholders(true)
            .build()).build()
Sampler answered 22/6, 2018 at 4:20 Comment(6)
Can you provide tour DataSource Implementation? How you use real-time data source with PagedList?Consolidation
@KeivanEsbati I have edited the question with that info. I used Room DatabaseSampler
@NickMowen how did u reversed the pagedList to have position 0 at the bottom?Boiling
@Boiling yes I didSampler
@NickMowen I'm sure you did. Can you please share HOW did you do that?Boiling
@Boiling just set the reverse layout flag on the layout manager constructor.. it's a simple Google for that oneSampler
S
40

It turns out that there is this beautiful thing called AdapterDataObsever which lets you observe the PagedListAdapter item calls. Here is how I was able to use it to solve the problem.

conversationAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
        override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
            if (positionStart == 0) {
                manager.scrollToPosition(0)
            }
        }
    })
Sampler answered 22/6, 2018 at 15:12 Comment(3)
This doesn't seem to work for me. The callback is invoked but the RecyclerView doesn't change position. Any idea what might cause this?Anastasia
@Anastasia If you don't have placeholders enabled and scroll to a position which isn't currently loaded it will not scrollSampler
Hi @NickMowen thank you for your feedback. What ended up working for me is I implemented all of the onItem change listeners AND enabled placeholders. Thank you.Anastasia

© 2022 - 2024 — McMap. All rights reserved.