如何在 Android 中使用 Paging 3 库显示空视图

Eri*_*Cen 8 android android-layout android-paging-3

我想在 paging3 加载空列表时显示空视图。

它似乎适用于以下代码。这是处理分页 3 库的正确方法吗?:

        adapter?.addLoadStateListener { loadState ->
            adapter?.apply {
                if (itemCount <= 0 && !loadState.source.refresh.endOfPaginationReached) {
                    Timber.d("==> to show empty view")
                    tvEmptyView.isGone = false
                } else {
                    Timber.d("==> to hide empty view")
                    tvEmptyView.isGone = true
                }
            }
        } 
Run Code Online (Sandbox Code Playgroud)

Flo*_*her 9

这对我有用:

if (loadState.source.refresh is LoadState.NotLoading &&
    loadState.append.endOfPaginationReached &&
    adapter.itemCount < 1
) {
   recyclerView.isVisible = false
   textViewEmpty.isVisible = true
} else {
    textViewEmpty.isVisible = false
}
Run Code Online (Sandbox Code Playgroud)


Pau*_*eke 5

您可以直接插入适配器loadStateFlow,例如

    lifecycleScope.launchWhenCreated {
        @OptIn(ExperimentalCoroutinesApi::class)
        adapter.loadStateFlow.collectLatest { loadStates ->
            val refresher = loadStates.refresh
            val displayEmptyMessage =  (refresher is LoadState.NotLoading && refresher.endOfPaginationReached && adapter.itemCount == 0)
            layoutBinding.emptyStateMessage.isVisible = displayEmptyMessage
            layoutBinding.emptyStateImage.isVisible = displayEmptyMessage
            layoutBinding.swipeToRefresh.isRefreshing = refresher is LoadState.Loading
        }
    }
Run Code Online (Sandbox Code Playgroud)