0

I have RecyclerView with 40 items. Item is a CardView with MotionLayout inside:

<androidx.cardview.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:cardView="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="2dp"
    cardView:cardCornerRadius="4dp"
    cardView:cardElevation="2dp">

<androidx.constraintlayout.motion.widget.MotionLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/motion_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layoutDescription="@xml/elements_catalog_item_scene">

    <ImageView
        android:id="@+id/element_icon"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:src="@drawable/ic_ca" />

    <TextView
        android:id="@+id/element_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="12dp"
        app:layout_constraintStart_toEndOf="@+id/element_icon"
        app:layout_constraintTop_toTopOf="@+id/element_icon"
        tools:text="element name" />

    <TextView
        android:id="@+id/element_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:visibility="gone"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/element_icon"
        tools:text="element description"/>

</androidx.constraintlayout.motion.widget.MotionLayout>
</androidx.cardview.widget.CardView>

When a user taps on any item, it expands and the user can see the element description below the element name. When the user taps on an expanded item, it collapses. The problem is - then the first item is expanded, if the user scrolls down the list, the 15th item is expanded too. And if the user collapses the 15th item, the first one will become collapsed as well. It works for all items 2 ->16 -> 31. etc I know, RecyclerView reuses views, I think I can store the state in my item list and give it to RecyclerView ViewHolder as payload, but how should I set the correct state of MotionLayout inside ViewHolder.bind()? Or can I do it just with RecyclerView settings?

Dmitry
  • 130
  • 6

1 Answers1

0

inside ViewHolder.bind(). You must set the stat of MotionLayout because the RecyclerView is recycling the layout.

hoford
  • 4,918
  • 2
  • 19
  • 19