-
如果您想在RecyclerView 中显示长列表,则绝对不要使用选项 1。将RecyclerView 放入NestedScrollView 将强制RecyclerView 一次创建所有项目。您将失去回收,并且您的应用程序可能会冻结以尝试创建所有 ViewHolders。它也会吃掉很多内存。 read more
-
选项 2 是实现具有不同布局类型的列表的主要方式。但它使创建列表的部分更加复杂。它至少不适用于Paging library 2。
幸运的是,我们现在有了更好的选择。
从RecyclerView 版本1.2.0-alpha02 开始,有一个新工具可用于轻松创建包含不同项目的复杂列表。它被称为ConcatAdapter。您可以在 Medium 上的 Florina Muntenescu 的 great article 中阅读更多相关信息。
截至 2020 年 5 月 10 日,库的最新版本是 1.2.0-alpha06。尽管库仍处于 alpha 版本,ConcatAdapter 是一个很棒的工具,自从它首次推出以来我一直在使用它。到目前为止,我从未遇到任何问题。它工作得很好,一切都很稳定。
根据我的经验,我想说这可能是在RecyclerView 中添加页眉和页脚(以及混合类型列表)的新的最佳实践。
ConcatAdapter 也用于Paging library version 3。在这个codelab 中,他们原生地向适配器添加了页眉和页脚。
binding.list.adapter = adapter.withLoadStateHeaderAndFooter(
header = ReposLoadStateAdapter { adapter.retry() },
footer = ReposLoadStateAdapter { adapter.retry() }
)
适配器扩展PagingDataAdapter。
如果您查看源代码,您会看到withLoadStateHeaderAndFoote 在后台使用ConcatAdapter。
/**
* Create a [ConcatAdapter] with the provided [LoadStateAdapter]s displaying the
* [LoadType.PREPEND] and [LoadType.APPEND] [LoadState]s as list items at the start and end
* respectively.
*
* @see LoadStateAdapter
* @see withLoadStateHeader
* @see withLoadStateFooter
*/
fun withLoadStateHeaderAndFooter(
header: LoadStateAdapter<*>,
footer: LoadStateAdapter<*>
): ConcatAdapter {
addLoadStateListener { loadStates ->
header.loadState = loadStates.prepend
footer.loadState = loadStates.append
}
return ConcatAdapter(header, this, footer)
}
所有这些都表明ConcatAdapter 开始被大量使用,并被证明是多类型列表的最佳解决方案。