使用 ViewGroup 作为列表?

Using a ViewGroup as a list?

在某些情况下,最好使用 ViewGroup to create lists, acting as something similar to a ListView, or RecyclerView

例如,我有一种情况需要在 ViewGroup 中显示项目列表,它是根布局的子级。 根布局是可滚动的(例如 ScrollView or NestedScrollView),因此使用另一个滚动 View 来显示列表项是不合适的。

这方面的一个例子是在 CardView 中显示列表项(当然在这种情况下,您不会想要太多列表项,因为卡片不适合这种情况)。在卡片中使用滚动布局显然是不正确的,尤其是当卡片是滚动根布局的一部分时。

另一个示例可能是创建导航抽屉(当然在 Google I/O 2015 年之后,有 Design Support Library,因此使用 NavigationView would be far simpler and easier). But before the Design Support Library, you had to populate a ViewGroup (likely a LinearLayout with items to display in the Navigation drawer, as the root layout of the drawer had to be scrollable. For more information about this scenario, I asked .

问题的关键是没有简单的方法可以使用 ViewGroup 作为列表布局,因此我们中的许多人倾向于使用复杂的解决方案来禁用 ListViewRecyclerView。是的,可以禁用 ListView 上的滚动,但通常仍会出现 Lint 警告。因此,使用 ViewGroup 列表也可以被认为是在滚动 Views.

上禁用滚动的替代解决方案

那么有没有一种简单的方法可以将 ViewGroup 用作列表?

受 Google 如何在导航抽屉的 LinearLayout 中填充列表项的启发,在他们的 2014 Google I/O 应用程序中,我创建了一个可以填充的 Gist列出 ViewGroup.

中的项目

要点,标题为 ViewGroupAdapter, can be found here

如果这个解决方案流行起来,我会继续更新和改进 Gist。