Как показать пустой вид с библиотекой Paging 3 в Android

Я хочу отображать пустое представление, когда 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
                }
            }
        } 

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
        }
    }

Это сработало для меня:

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

В моем случае мне пришлось использовать concatAdapter для отображения пустого представления под нормальными результатами, если они меньше 11. К сожалению, библиотека подкачки 3 даст мне много ложноположительных результатов в отношении LoadState.NotLoading и 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
    }
Другие вопросы по тегам