所以我尝试实现分页库,但是由于 PageKeyedDataSource 是一个抽象类,所以我无法在Fragment中实现它。
这是我到目前为止所做的,但是正如您在我的API调用中所看到的那样,我正在制作该片段的实例-categoryFragment.getCategoryName()是执行此操作的一种不好的方法。我不知道该如何传递,因为我不能使用sharedPreferences。
片段
public void callComponents() {
mainActivityViewModel.getPagedListLiveData().observe(this, new Observer<PagedList<Component.Rows>>() {
@Override
public void onChanged(@Nullable PagedList<Component.Rows> photos) {
componentAdapter = new ComponentAdapter(getActivity(),photos);
componentAdapter.submitList(photos);
recyclerView.setAdapter(componentAdapter);
}
});
API调用
List<Component.Rows> list;
CategoryFragment categoryFragment = new CategoryFragment();
@Override
public void loadInitial(@NonNull LoadInitialParams<Long> params, @NonNull final LoadInitialCallback<Long, Component.Rows> callback) {
JsonPlaceHolderApi api = ApiClient.getClient().create(JsonPlaceHolderApi.class);
Call<Component.Rows> data =
api.listComponents(API,categoryFragment.getCategoryName(),"purchase_cost");
list = new ArrayList<>();
data.enqueue(
new Callback<Component.Rows>() {
@Override
public void onResponse(Call<Component.Rows> call, Response<Component.Rows> response) {
for (int i = 0; i < response.body().getRows().size(); i++) {
Component.Rows photosList = response.body();
list.add(photosList);
}
callback.onResult(list,
null, (long) 2);
}
@Override
public void onFailure(Call<Component.Rows> call, Throwable t) {
}
});
...other methods
}
ViewModel
public MainActivityViewModel(@NonNull Application application) {
super(application);
photoDataSourceFactory = new PhotoDataSourceFactory();
dataSourceMutableLiveData = photoDataSourceFactory.getMutableLiveData();
PagedList.Config config = (
new PagedList.Config.Builder())
.setEnablePlaceholders(
true)
.setInitialLoadSizeHint(10)
.setPageSize(4)
.setPrefetchDistance(4)
.build();
executor = Executors.newFixedThreadPool(5);
pagedListLiveData = (new LivePagedListBuilder<Long, Component.Rows>(photoDataSourceFactory, config))
.setFetchExecutor(
executor)
.build();
}
public LiveData<PagedList<Component.Rows>> getPagedListLiveData() {
return pagedListLiveData;
}
}