如何在工具中显示多个布局:RecyclerVIew xml 的列表项命名空间

我有一个 RecyclerView 具有不同类型的 ViewHolders,它们具有不同的布局资源。有没有办法在 tools:listItem 命名空间中指定所有布局?如果我像这样指定所有 listItems 布局:

 <androidx.recyclerview.widget.RecyclerView

        ......

        tools:listitem="@layout/layout_1"
        tools:listitem="@layout/layout_2"
        tools:listitem="@layout/layout_3" />

由于重复的项目,我遇到了错误。我可以这样做:

 <androidx.recyclerview.widget.RecyclerView
  
        ......

        tools:listitem0="@layout/layout_1"
        tools:listitem1="@layout/layout_2"
        tools:listitem2="@layout/layout_3" />

错误没有出现,但是打开布局的点击功能丢失了,因为命名空间中没有这样的声明。 使用 tools:showIn 时也是一样。

catheone 回答:如何在工具中显示多个布局:RecyclerVIew xml 的列表项命名空间

tools:listitem 属性仅接受一种项目类型,因此一种可行且简单的方法是使用 <include/> 标记和 LinearLayout 的父项在单独的 xml 文件中定义所有不同的布局。>

1.创建 res->layout->item_multiple_layouts.xml 并使用垂直线性布局按照您希望在 RecyclerView 中出现的顺序定义所有布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <include layout="@layout/item_type_1" />
    <include layout="@layout/item_type_2" />
    <include layout="@layout/item_type_3" />
    <include layout="@layout/item_type_1" />
    <include layout="@layout/item_type_2" />
    <include layout="@layout/item_type_3" />

</LinearLayout>

2.要在 RecyclerView 中预览上述布局,您可以使用 itemCount=1 指向上述布局以仅渲染一次,如下所示:

<androidx.recyclerview.widget.RecyclerView
    tools:listitem="@layout/item_multiple_layouts"
    tools:itemCount="1"/>
,

我认为没有任何干净的方法可以做到这一点。 如果您想预览多个项目的相同布局,您可以执行以下操作:

tools:listitem="@layout/layout_1"
tools:itemCount="5"

为此目的,有一种不同的方法来实现自定义 ViewFlipper。但我觉得这太过分了。我将只运行应用程序而不是编写该代码:P

链接如下: https://medium.com/@AllanHasegawa/previewing-multiples-item-types-in-a-recyclerview-163aebc2f34a

本文链接:https://www.f2er.com/48812.html

大家都在问