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

问题描述

分页3加载空列表时,我想显示空视图。

似乎可以使用以下代码。这是使用分页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
                }
            }
        } 

解决方法

您可以直接插入适配器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
        }
    }
,

这对我有用:

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

在我的情况下,如果它们小于 11,我不得不使用 concatAdapter 来显示下面正常结果的空视图。不幸的是,分页 3 库会给我很多关于 {{ 1}} 和 LoadState.NotLoading 状态,所以我不得不通过引入一个计数器来仔细检查它。弗洛里安或保罗的答案都会起作用。

loadState.append.endOfPaginationReached