Android 第 3 页未加载下一页

Android Paging 3 is not loading next page

从自定义分页实施迁移到 Jetpack Paging 3 库后, 数据未按预期加载。 首页根据PagerPagingConfig正确处理:

internal fun createProductListPager(pagingSource: ProductListPagingSource): Pager<Int, Product> = Pager(
    config = PagingConfig(
        pageSize = 10,
        prefetchDistance = 2,
    ),
    initialKey = 0,
) { pagingSource }

这是 Adapter 的摘录:

public class PagingProductCardAdapter(private val viewBinder: CoreViewBinder) :
    PagingDataAdapter<Listable, RecyclerView.ViewHolder>(viewBinder.getDiffUtils()) {


    public val list: List<Listable>
        get() = snapshot().items


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
      // ...
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        viewBinder.bind(list[position], holder)
    }
    // ...
}

当滚动到 RecyclerView 底部时,下一页根本没有加载(没有调用PagingSource.load()) 会出什么问题?

PagingSource 如何知道何时加载更多数据?它背后有什么魔力?
好吧,结果是 适配器负责这个 Adapter 如何知道加载的数据? 您必须按照记录调用 getItem()

/**
 * Returns the presented item at the specified position, notifying Paging of the item access to
 * trigger any loads necessary to fulfill [prefetchDistance][PagingConfig.prefetchDistance].
 *
 * @param position Index of the presented item to return, including placeholders.
 * @return The presented item at [position], `null` if it is a placeholder
 */
protected fun getItem(@IntRange(from = 0) position: Int) = differ.getItem(position)

当我们通过快照访问整个列表时:

public val list: List<Listable>
    get() = snapshot().items

适配器不知道正在加载什么项目,也无法触发下一页加载。

所以修复是:

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    getItem(position)?.let {
        viewBinder.bind(list[position], holder)
    }
}

有了这个,一切正常!