首页 > 解决方案 > 在 PageKeyedDataSource 中设置 DataSource 大小以获得占位符效果

问题描述

我正在使用Android Architecture Component中的分页库。我正在尝试通过服务器加载数据,没有任何本地数据库。

我的DataSource课扩展了PageKeyedDataSource

下面是我的Paging.Config定制,

PagedList.Config pageConfig = (new PagedList.Config.Builder())
            .setPageSize(20)
            .setInitialLoadSizeHint(30)
            .setPrefetchDistance(5)
            .setEnablePlaceholders(true)
            .build();

我启用了占位符,这让我可以nullPagedListAdapter课堂上进行管理。我做了类似下面的事情,

@Override
public void onBindViewHolder(@NonNull MyEventViewHolder holder, int position) {
    Article mArticle = getItem(position);

    if (mArticle != null) {
        holder.txtTitle.setText(mArticle.getTitle());
        holder.txtAuthor.setText(mArticle.getAuthor());
        holder.txtDesc.setText(mArticle.getDescription());
    } else {
        holder.txtTitle.setText("...");
        holder.txtAuthor.setText("......");
        holder.txtDesc.setText(".........");
    }
}

在下一次 API 调用之前,我无法在列表末尾看到占位符。

我的问题是,有没有办法可以在第一次 API 调用后指定列表的大小 ?由于我的 API 正在返回查询中预期的项目总数。如果不可能,我还能做些什么来查看我的列表的占位符。

注意:我无法切换到ItemKeyedDataSourcePositionalDataSource因为我的 API 设置为基于页面响应。

标签: androidandroid-layoutandroid-recyclerviewandroid-jetpackandroid-paging

解决方案


为此我认为你需要在里面做 loadInitial

callback.onResult(mArticles, 0, SIZE_OF_TOTAL_ITEMS, null, 2L);

加载之前

callback.onResult(mArticles, params.key - 1);

加载后

callback.onResult(mArticles, params.key + 1);

并且在初始加载时必须知道 SIZE_OF_TOTAL_ITEMS。


推荐阅读