需求: *常规列表,有刷新,加载(异常,底部)
依赖:
//Paging
def paging_version = "3.0.1"
implementation "androidx.paging:paging-runtime:$paging_version"
implementation "androidx.paging:paging-guava:$paging_version"
testImplementation "androidx.paging:paging-common:$paging_version"
布局
展示代码
recyclerView.setLayoutManager(new LinearLayoutManager(requireContext()));
_adapter = new InnerAdapter();
//刷新UI
_adapter.addLoadStateListener(new SmartLoadStateListener(_adapter, _binding.refresh));
//加载更多UI
ConcatAdapter adapter = _adapter.withLoadStateFooter(new LoadMoreStateAdapter(getLayoutInflater(), _adapter));
_binding.recyclerView.setAdapter(adapter);
_viewModel.getOrders().observe(getViewLifecycleOwner(), result -> {
_adapter.submitData(getLifecycle(), result);
});
SmartLoadStateListener:响应刷新UI
@Override
public Unit invoke(CombinedLoadStates combinedLoadStates) {
LoadState refresh = combinedLoadStates.getRefresh();
if (refresh instanceof LoadState.Loading) {
_layout.autoRefreshAnimationOnly();
} else {
_layout.finishRefresh();
}
return null;
}
LoadMoreStateAdapter:让没有更多的状态可以展示
@Override
public boolean displayLoadStateAsItem(@NonNull LoadState loadState) {
return super.displayLoadStateAsItem(loadState)
|| (loadState instanceof LoadState.NotLoading && loadState.getEndOfPaginationReached());
}
ViewModel:提供数据给View
public LiveData> getOrders() { if (null == data) { Pager pager = this.orderRepository.getExceptionOrders(30); CoroutineScope viewModelScope = ViewModelKt.getViewModelScope(this); LiveData > source = PagingLiveData.cachedIn(PagingLiveData.getLiveData(pager), viewModelScope); data = Transformations.map(source, pagingData -> PagingDataTransforms.map(pagingData, AppAgent.getInstance().getWorkExecutor(), ExceptionOrderModel::new)); } return data; }
PagingSource
@Nullable
@Override
public Integer getRefreshKey(@NonNull PagingState pagingState) {
return null;
}
@NonNull
@Override
public ListenableFuture> loadFuture(@NonNull LoadParams loadParams) {
int page = loadParams.getKey();
int size = loadParams.getLoadSize();
ListenableFuture>> task = Futures.submit(() -> dataSource.loadExceptionOrders(page, size), executor);
return Futures.transform(task, input -> toLoadResult(input, page, size), executor);
}
private LoadResult toLoadResult(Result> result, int page, int size) {
if (result instanceof Result.Success) {
Result.Success> success = (Result.Success>) result;
if (success.getData().size() == size) {
return new LoadResult.Page<>(
success.getData()
, null
, page + 1
);
} else {
return new LoadResult.Page<>(
success.getData()
, null
, null
);
}
} else {
Result.Fail> fail = (Result.Fail>) result;
return new LoadResult.Error<>(new LoadErrorException(fail.getMsg()));
}
}
需要注意的一点,_adapter.withLoadStateFooter() 会返回一个Adapter,将这个Adapter绑定给recyclerView,才能展示Footer 或者 Headter



