Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to animate the change of a layout manager of recycler view

I am using a recycler view with 2 different layout layout manager which is LinearLayoutManager and GridLayoutManager.

I would like to animate the items when switching from one layout manager to another manager. Is there a way to achieve this effect?

The approached pops up in my head is to override the setLayoutManger method and capture the BEFORE states of the items using the fromLayoutManager and calculate the AFTER states of the items using the toLayoutManager and animate those items into place.

I have not investigate deeply into the codes, so anyone could tell me that is such approach achievable or is there better to achieved this?

like image 839
Morty Choi Avatar asked Mar 18 '15 09:03

Morty Choi


People also ask

What is transition animation in Android?

Android Transition Framework can be used for three main things: Animate activity layout content when transitioning from one activity to another. Animate shared elements (Hero views) in transitions between activities. Animate view changes within same activity.

What is layout manager in RecyclerView?

A LayoutManager is responsible for measuring and positioning item views within a RecyclerView as well as determining the policy for when to recycle item views that are no longer visible to the user.


1 Answers

I solved this by adding the two methods below to my adapter. I call notifyRemoveEach(), change the layout manager, and then call notifyAddEach(). The items are briefly animated out/in depending on the duration specified on your ItemAnimator.

    public void notifyRemoveEach() {
        for (int i = 0; i < items.size(); i++) {
            notifyItemRemoved(i);
        }
    }

    public void notifyAddEach() {
        for (int i = 0; i < items.size(); i++) {
            notifyItemInserted(i);
        }
    }
like image 192
Andy Dyer Avatar answered Sep 27 '22 21:09

Andy Dyer