Search code examples
androidanimationandroid-recyclerview

Animate RecyclerView height


Is it possible to animate RecyclerView height, or otherwise change it programmatically? For example, if I have a large header view that is sometimes visible, and other times not - I would want to animate the RecyclerView height to fill the screen when the header is animated out.

Changing LayoutParams.height does not seem to work. LinearLayout animateLayoutChanges causes a crash.

<LinearLayout>
   <RelativeLayout (header)>
   <RecyclerView>
</LinearLayout>

I want to make the RelativeLayout animate out the top (translationY) and then at the same time make the recyclerview animate to be taller to fit.


Solution

  • There are possible options to tackle this:

    1. Follow suggestion from @Ari to start animation and on every animation tick update layout params. This will make an effect of recyclerview changing its size. However, this is a horrible idea from performance stand point. Layout and Measure process is quite expensive, so generally you want to minimize calls which trigger layout. Call to setLayoutParams will trigger layout & measure process for RecyclerView + all its children which means that on every single frame you will do really expensive work which most likely will lead to framedrop and bad user experience

    2. There is another way though. It might not work in all cases - it all depends on your final layout, but still that's what I would recommend doing. The idea - is to make your recyclerView taller before you start animation. It requires some advanced Android skills though. Basically you need to override onMeasure & layout methods in your RecyclerView (you actually need to extend RecyclerView class to do that).

      • You can introduce some flag to your recyclerView to measure itself a bit taller than normal (how much taller - the exact height of your header view)
      • when you need to animate header out - set your flag to true and request new layout. This will re-layout recyclerView with some invisible part at the bottom.
      • Now you can just animate y translations of both RecyclerView & Header so header moves out of the screen and recyclerview goes higher. This will make user feel like recyclerview "expands"
      • Once animation is done - set your custom flag to false and change visibility of your header to GONE since it is off screen now

    Here is some information about implementing custom onMeasure logic: https://medium.com/android-news/perfmatters-introduction-to-custom-viewgroups-to-improve-performance-part-2-f14fbcd47c