【发布时间】:2021-02-04 17:03:40
【问题描述】:
按照此处提供的说明,我已经能够成功实现新的 alpha07 版本的 Paging 3 库:https://developer.android.com/topic/libraries/architecture/paging/v3-paged-data#guava-livedata
但是,现在我需要检查返回的列表是否为空,以便向用户显示视图或文本,但我无法在其分页设计的流程结构中附加任何检查.
目前,在遵循他们的指南后,我在 onViewCreated 中使用 Java 编写代码的方式如下:
MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
LifecycleOwner lifecycleOwner = getViewLifecycleOwner();
Lifecycle lifecycle = lifecycleOwner.getLifecycle();
Pager<Integer, MyEntity> pager = new Pager<>(new PagingConfig(10), () -> viewModel.getMyPagingSource());
LiveData<PagingData<MyEntity>> pagingDataLiveData = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), lifecycle);
pagingDataLiveData.observe(lifecycleOwner, data -> adapter.submitData(lifecycle, data));
我尝试在adapter.submitData(lifecycle, data) 中的data 上附加.filter,但尽管列表为空,但它从未收到null 项目。
在这种情况下如何检查提交给适配器的数据何时为空?我在他们的文档中找不到任何指针。
编辑:这是我找到的解决方案,在这里发布是因为选择的答案严格来说不是解决方案,也不是 java 中的解决方案,而是引导我找到它的答案。
我必须在我的适配器上附加一个LoadStateListener,监听LoadType 何时为REFRESH 并且LoadState 为NotLoading,然后检查adapter.getItemCount 是否为0。
可能一个不同的LoadType 更适合这种情况,但到目前为止刷新对我来说是有效的,所以我选择了那个。
示例:
// somewhere when you initialize your adapter
...
myAdapter.addLoadStateListener(this::loadStateListener);
...
private Unit loadStateListener(@Nonnull CombinedLoadStates combinedLoadStates) {
if (!(combinedLoadStates.getRefresh() instanceof LoadState.NotLoading)) {
return Unit.INSTANCE; // this is the void equivalent in kotlin
}
myView.setVisibility(adapter.getItemCount() == 0 ? View.VISIBLE : View.INVISIBLE);
return Unit.INSTANCE; // this is the void equivalent in kotlin
}
注意:我们必须返回 Unit.INSTANCE,因为该侦听器在 kotlin 中,并且该代码正在 java 中使用,返回它相当于在 java (void) 中不返回任何内容。
【问题讨论】:
标签: android android-paging android-paging-library