如何在使用Android Paging 3库时显示空白视图 [英] How to show empty view while using Android Paging 3 library

查看:113
本文介绍了如何在使用Android Paging 3库时显示空白视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Paging 3 lib.并且我能够检查刷新状态是否为正在加载"或错误"但是我不确定如何检查空"状态.我可以添加以下条件,但不确定其条件是否正确

I am using Paging 3 lib. and i am able to check if refresh state is "Loading" or "Error" but i am not sure how to check "empty" state.I am able to add following condition but i am not sure if its proper condition

adapter.loadStateFlow.collectLatest { loadStates ->
                viewBinding.sflLoadingView.setVisibility(loadStates.refresh is LoadState.Loading)
                viewBinding.llErrorView.setVisibility(loadStates.refresh is LoadState.Error)
                viewBinding.button.setOnClickListener { pagingAdapter.refresh() }

                if(loadStates.refresh is LoadState.NotLoading && (viewBinding.recyclerView.adapter as ConcatAdapter).itemCount == 0){
                    viewBinding.llEmptyView.setVisibility(true)
                }else{
                    viewBinding.llEmptyView.setVisibility(false)
                }
            } 

我也遇到其他问题我已经实现了搜索功能,直到输入了2个以上的字符,我才使用如下所示的相同页面资源,但是上述loadstate回调仅执行一次.这样做是为了保存来自前端的api调用.

Also I am running into other problem I have implemented search functionality and until more than 2 characters are entered i am using same paging source like following but the above loadstate callback is executed only once.So thats why i am not able to hide empty view if search query is cleared.I am doing so to save api call from front end.

private val originalList : LiveData<PagingData<ModelResponse>> = Transformations.switchMap(liveData){
        repository.fetchSearchResults("").cachedIn(viewModelScope)
    }

    val list : LiveData<LiveData<PagingData<ModelResponse>>> = Transformations.switchMap{ query ->
        if(query != null) {
            if (query.length >= 2)
                repository.fetchSearchResults(query)
            else
                originalList
        }else
            liveData { emptyList<ModelResponse>() }
    } 

推荐答案

以下是在Android Paging 3中处理空视图的正确方法:

Here is the proper way of handling the empty view in Android Paging 3:

adapter.addLoadStateListener { loadState ->
            if (loadState.source.refresh is LoadState.NotLoading && loadState.append.endOfPaginationReached && adapter.itemCount < 1) {
                recycleView?.isVisible = false
                emptyView?.isVisible = true
            } else {
                recycleView?.isVisible = true
                emptyView?.isVisible = false
            }
        }

这篇关于如何在使用Android Paging 3库时显示空白视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆