How to show multiple layout in tools:listitem namespace of the RecyclerVIew xml

Viewed 331

I have a RecyclerView with different Types of ViewHolders, that have different layout resources. Is there a way to specify all layouts in the tools:listItem namespace? If I specify all listItems layout like this:

 <androidx.recyclerview.widget.RecyclerView

        ......

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

I got an error because of duplicated items. I could do something like this:

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

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

The error is not presented but the clicking functionality that opens the layout is lost because there is no such declaration in the namespace. It is the same when tools:showIn is used.

2 Answers

The tools:listitem attribute accepts only a single item type so one possible and easy way is to define all your different layouts in a separate xml file using the <include/> tag with a parent of LinearLayout.

1.Create res->layout->item_multiple_layouts.xml and define all your layouts in the order you wish to appear in the RecyclerView using a Vertical LinearLayout:

<?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.To preview the above layouts in the RecyclerView you can point to the above layout with itemCount=1 to render them only once like below:

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