A. Patrik
A. Patrik

Reputation: 1692

Can I use MotionLayout to animate individual items inside RecyclerView?

I want to create expandable items, inside a recyclerview, and I thought, using MotionLayout to create the animation would be super easy. I created the motion scene and tested that a single item works on its own when inside a recycler view the view won't animate.

I tried showing all debug info, and it said that the transitions are happening, but the recyclerview did not show any animations. I tried notifying the item animator that animation has started on my viewholder, but that did not work.

override fun onTransitionStarted(p0: MotionLayout?, p1: Int, p2: Int) {
  recyclerView.itemAnimator?.onAnimationStarted(this@ViewHolder)
}
override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) {
  recyclerView.itemAnimator?.onAnimationFinished(this@ViewHolder)
}

I expected that motinolayout state transitions would work inside recyclerview, but they don't seem to be working.

Single list item: enter image description here

Inside list: enter image description here

Upvotes: 4

Views: 1385

Answers (2)

Onregs
Onregs

Reputation: 430

Try to update your ConstraintLayout to androidx.constraintlayout:constraintlayout:2.0.0-rc1 seems this bag was fixed, as well as RecyclerView androidx.recyclerview:recyclerview:1.2.0-alpha05.

Upvotes: 2

Darish
Darish

Reputation: 11481

I want to create expandable items, inside a recyclerview, and I thought, using MotionLayout to create the animation would be super easy.

Using MotionLayout inside RecyclerView for simple expand animation is overkill, you can get the same animation simply by using simple view/hide on the RecyclerView Adapter onBindViewHolder. Then when ever you want to expand/collapse, simply call notifyItemchanged with position. That will save your day. cheers!

Inside the RecyclerView Adapter,

holder.itemView.setOnClickListener(v -> {
    // Get the current state of the item
    boolean expanded = item.isExpanded();
    // Change the state
    item.setExpanded(!expanded);
    // Notify the adapter that item has changed
    notifyItemChanged(position);
});

Upvotes: 3

Related Questions