Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly scroll after item inserted into PagedListAdapter

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()
like image 541
Nick Mowen Avatar asked Jun 22 '18 04:06

Nick Mowen


1 Answers

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)
            }
        }
    })
like image 156
Nick Mowen Avatar answered Oct 18 '22 19:10

Nick Mowen