kotlin 使用分页库3显示进度条后加载新项目

yzuktlbb  于 2022-11-25  发布在  Kotlin
关注(0)|答案(2)|浏览(139)

我已经实现了分页库3,它工作并显示数据,我需要实现的是加载更多的功能,所以当用户向下滚动时,它会获取一个页面10项,所以基本上在加载新数据之间,我想在底部显示一个进度条,但由于这是我第一次使用分页库3,我不知道如何做到这一点,如果有人能,我会很感激。谢谢你

  • 我尝试根据适配器类的loadstate显示和隐藏进度条,但没有成功
lifecycleScope.launch {
           newsAdapter.loadStateFlow.collectLatest { loadingState ->
               if(loadingState.refresh is LoadState.Loading){
                   binding.progressBar.visibility = View.GONE
               }
               if(loadingState.refresh is LoadState.Loading) {
                   binding.progressBar.visibility = View.VISIBLE
               }
               if(loadingState.refresh is LoadState.NotLoading){
                   binding.progressBar.visibility = View.GONE
               }

           }
       }
ercv8c1e

ercv8c1e1#

用于向下滚动的LoadStateCombinedLoadStates.append,而不是.refresh.refresh是列表被替换的时间(初始加载/刷新)。
实际上,如果您对ConcatAdapter样式的LoadState感知页脚感兴趣,分页有一个内置的功能,请参见:https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data#load-state-adapter

ukxgm1gy

ukxgm1gy2#

查看https://medium.com/@yash786agg/jetpack-paging-3-0-android-bae37a56b92d,我发现我们也应该观察append状态,正如@dlam所写的那样。

adapter.addLoadStateListener { loadState ->

    if (loadState.refresh is LoadState.Loading ||
        loadState.append is LoadState.Loading)
        // Show ProgressBar
    else {
        // Hide ProgressBar

        // If we have an error, show a toast
        val errorState = when {
            loadState.append is LoadState.Error -> loadState.append as LoadState.Error
            loadState.prepend is LoadState.Error ->  loadState.prepend as LoadState.Error
            loadState.refresh is LoadState.Error -> loadState.refresh as LoadState.Error
            else -> null
        }
        errorState?.let {
            Toast.makeText(this, it.error.toString(), Toast.LENGTH_LONG).show()
        }
    }
}

相关问题