Android Paging 3不显示Loadstate适配器

问题描述

我已按照教程在Android Paging 3上将Loadstate Adapter添加到Recyclerview Adapter,但目前未显示。这就是我更新适配器的方式。

 lifecycleScope.launch {
            viewmodel.searchProducts(searchParam,channelId,categoryId)
                .collectLatest {
                    binding.allProductRecyclerView.isVisible = true
                    adapter.submitData(it)
                }
        

这就是我添加LoadState适配器的方式

  binding.allProductRecyclerView.adapter = adapter.withLoadStateFooter(
        footer = ProductLoadingStateAdapter()
    )

StorybookThis is the gist of LoadStateAdapterActivity Layout

适配器工作正常,我也可以通过添加LoadStateListener来获取负载状态。只是负载状态适配器不起作用。我已经跟踪并克隆了load state Item,它运行良好。我的问题可能是什么?

解决方法

尝试像这样在您的ProductLoadingStateAdapter中覆盖以下方法:

class ProductLoadingStateAdapter: LoadStateAdapter<XXX>() {
   override fun onBindViewholder...

   override fun onCreateViewHolder...
  
   override fun displayLoadStateAsItem(loadState: LoadState): Boolean {
      return loadState is LoadState.Loading || loadState is LoadState.Error || LoadState.NotLoading
   }
}

如果查看LoadStateAdapter的源代码,则默认情况下,它仅向适配器发出“正在加载”和“错误”加载状态,这意味着适配器将不知道加载过程是否已完成。

因此,在您的情况下,以下代码将始终导致progress.visibilityVISIBLE。因为您只能在LoadState.Loading中获得onBindViewHolder状态。

//loadState is always LoadState.Loading
if (loadState is LoadState.Loading) progress.visibility =
            View.VISIBLE; txtErrorMessage.visibility = View.GONE