回收商视角的标题,2020 年的最佳实践是什么?

use*_*123 0 android android-recyclerview

我有一个回收者的观点。我想向回收站视图添加一个标题,以便它与回收站视图一起滚动。多年前,选项是:

  1. 将回收器视图和标题布局嵌套在NestedScrollView. 这样做的缺点是这意味着回收者视图不会像它应该的那样运行。
  2. 修改回收器视图,使其处理两种视图类型,一种用于标题,另一种用于常规回收器视图项。

2020年我们在哪里?这仍然是两种选择吗?如果是这样,#2 仍然是推荐的选项吗?

谢谢。

Mar*_*rat 5

  • 如果您想在RecyclerView. 放置RecyclerViewNestedScrollView将迫使RecyclerView一次创建的所有项目。您将失去回收,并且您的应用程序可能会在尝试创建所有 ViewHolders 时冻结。它也会占用大量内存。阅读更多

  • 选项 2 是在其中实现具有不同布局类型的列表的主要方法。但它使创建列表的部分变得更加复杂。它至少不适用于Paging library 2

幸运的是,我们现在有了更好的选择。

RecyclerView版本1.2.0-alpha02开始,有一个新工具可用于轻松创建包含不同项目的复杂列表。它被称为ConcatAdapter。您可以在Florina Muntenescu 在 Medium 上发表的一篇很棒的文章中阅读更多相关信息。

截至 20 年 5 月 10 日,库的最新版本为 1.2.0-alpha06。尽管库仍处于 alpha 版本,但它ConcatAdapter是一个很棒的工具,自首次推出以来我一直在使用它。到目前为止,我从未遇到任何问题。它工作得很好,一切都非常稳定。

根据我的经验,我会说这可能RecyclerView.

ConcatAdapter也用于分页库版本 3。在此代码实验室中,他们将页眉和页脚原生添加到适配器中。

binding.list.adapter = adapter.withLoadStateHeaderAndFooter(
        header = ReposLoadStateAdapter { adapter.retry() },
        footer = ReposLoadStateAdapter { adapter.retry() }
)
Run Code Online (Sandbox Code Playgroud)

和适配器扩展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)
}
Run Code Online (Sandbox Code Playgroud)

所有这些都表明它ConcatAdapter开始被大量使用,并被证明是多类型列表的最佳解决方案。