0
 mAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
            override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
                if (positionStart == 0) {
                    LogUtils.d("================= scroll to top")
                    binding.rv.layoutManager?.scrollToPosition(0)
                    autoScrollToStartFlag = false
                }
            }
        })

我希望 recyclerView 在插入新项目时滚动到顶部,它适用于上面的代码。然后我使用下一个代码将分隔符添加到 recyclerVeiw, binding.rv.layoutManager?.scrollToPosition(0)不再起作用。

Pager(...)
    .flow
    .map { pagingData ->
            pagingData.map {
                UiModel.SyncUiModel(it)
            }
                .insertSeparators<UiModel.SyncUiModel, UiModel>{ model: UiModel.SyncUiModel?, model2: UiModel.SyncUiModel? ->
                    LogUtils.d("================= before: ${model?.id ?: "empty"} after: ${model2?.id ?: "empty"}")
                    if (model == null) return@insertSeparators UiModel.SeparatorModel("head")
                    if (model2 == null) return@insertSeparators UiModel.SeparatorModel("foot")
                    return@insertSeparators null
                }
        }.cachedIn(viewModelScope)

日志 :

================= scroll to top
================= before: empty after: 953
================= before: 953 after: 952
================= before: 952 after: 950
================= before: 950 after: 949
================= before: 949 after: 946
================= before: 946 after: 944
================= before: 944 after: 937

似乎binding.rv.layoutManager?.scrollToPosition(0)在 insertSeparators 之前执行得太早了。

4

0 回答 0