10

当 paging3 加载一个空列表时,我想显示空视图。

它似乎适用于以下代码。这是使用 paging 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
                }
            }
        } 
4

3 回答 3

4

这对我有用:

if (loadState.source.refresh is LoadState.NotLoading &&
    loadState.append.endOfPaginationReached &&
    adapter.itemCount < 1
) {
   recyclerView.isVisible = false
   textViewEmpty.isVisible = true
} else {
    textViewEmpty.isVisible = false
}
于 2020-12-16T14:10:06.970 回答
3

您可以直接插入适配器 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
        }
    }
于 2020-12-06T10:51:30.007 回答
0

在我的情况下,如果它们小于 11,我必须使用 concatAdapter在正常结果下方LoadState.NotLoading显示空视图。不幸的是,分页 3 库会给我很多关于和状态的误报结果,loadState.append.endOfPaginationReached所以我不得不通过引入一个来仔细检查它柜台。弗洛里安或保罗的答案都行得通。

     offersAdapter.addLoadStateListener { updateUiOnNewLoadSate(it) }
    
     private fun updateUiOnNewLoadSate(loadState: CombinedLoadStates) {
    
            Timber.i("STATE $loadState")
          
            // Show empty view if results are less or equal 10
            val displayEmptySearch =
                loadState.source.refresh is LoadState.NotLoading && loadState.append.endOfPaginationReached && offersAdapter.itemCount <= 10 && loadStatesCounter > 1
            if (displayEmptySearch) {
    //here I display the empty view as a part of the
   //infinite scrolling recyclerview by using concatAdapter
                concatAdapter.addAdapter(emptyViewAdapter)
            } else {
                concatAdapter.removeAdapter(emptyViewAdapter)
            }
            loadStatesCounter++ //only apply above block when loadStatesCounter > 1
    }
于 2021-03-21T15:39:15.107 回答