<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nikhil Panju on Medium]]></title>
        <description><![CDATA[Stories by Nikhil Panju on Medium]]></description>
        <link>https://medium.com/@nikhilpanju22?source=rss-f3034e2b0e9d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*StjP_cQSwGtqXTFCGxHGaA.jpeg</url>
            <title>Stories by Nikhil Panju on Medium</title>
            <link>https://medium.com/@nikhilpanju22?source=rss-f3034e2b0e9d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 19:27:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nikhilpanju22/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Complex UI/Animations on Android — featuring MotionLayout]]></title>
            <link>https://proandroiddev.com/complex-ui-animations-on-android-featuring-motionlayout-aa82d83b8660?source=rss-f3034e2b0e9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa82d83b8660</guid>
            <category><![CDATA[ux]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Nikhil Panju]]></dc:creator>
            <pubDate>Thu, 30 Jan 2020 18:59:16 GMT</pubDate>
            <atom:updated>2020-02-06T19:02:05.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iJMugDxk4IxBbCIjWOgs9w.png" /></figure><h3>Complex UI/Animations on Android — featuring MotionLayout</h3><p>Exploring complex multi-step animations with MotionLayout (and Coroutines).</p><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fgfycat.com%2Fhairywellworngelding&amp;src=https%3A%2F%2Fgfycat.com%2Fifr%2Fhairywellworngelding&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=gfycat" width="1280" height="1280" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fcaa733b17ed55a98c37dc89f6ebd7a/href">https://medium.com/media/4fcaa733b17ed55a98c37dc89f6ebd7a/href</a></iframe><blockquote><a href="https://developer.android.com/training/constraint-layout/motionlayout">MotionLayout</a> is the new kid on the block for animations, transitions, complex motions, what-have-you. In this article, we’re going to look at how MotionLayout and Coroutines can help us structure multi-step animations.</blockquote><p>The previous article dives into all the different animations and widgets without using MotionLayout. I encourage you to read it because:</p><ol><li>We will only be going into the filter sheet transitions in this article and not the adapter, tabs and other animations.</li><li>You can understand and appreciate the differences in writing these animations with and without using MotionLayout.</li></ol><p><a href="https://proandroiddev.com/complex-ui-animation-on-android-8f7a46f4aec4">Complex UI/Animation on Android</a></p><h3>Before we begin</h3><ul><li><strong>TLDR? </strong><a href="https://github.com/nikhilpanju/FabFilter"><strong>View the source code on Github.</strong></a> It’s well documented and contains code for both; with and without MotionLayout.</li><li><a href="https://play.google.com/store/apps/details?id=com.nikhilpanju.fabfilter"><strong>Download the app on the PlayStore</strong></a> or build the source code to demo the app. (Don’t forget to check the <strong>“Use MotionLayout”</strong> checkbox in the Nav Drawer).</li></ul><h3>What is MotionLayout? A quick intro…</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ddULlE7YKRVeneFY2IDqw.png" /></figure><p>Simply put, MotionLayout is a ConstraintLayout that allows you to easily transition between two ConstraintSets.</p><p>&lt;ConstraintSet&gt; contains all the constraints and layout attributes for each view.</p><p>&lt;Transition&gt; specifies the starting and ending ConstraintSets to transition between.</p><p>Throw all of this into a &lt;MotionScene&gt; file and you have yourself a MotionLayout!</p><p>As layouts and animations become more complex, the MotionScene also becomes more elaborate. We’re going to take a look at these components.</p><h4>Learn more about MotionLayout:</h4><p><strong>#1 </strong>Nicolas Roard’s <a href="https://medium.com/google-developers/introduction-to-motionlayout-part-i-29208674b10d">Introduction to MotionLayout</a> Series.<br><strong>#2</strong> James Pearson’s <a href="https://www.droidcon.com/media-detail?video=362742385">Advanced &amp; Practical MotionLayout</a> Talk.<br><strong>#3</strong> Official <a href="https://developer.android.com/training/constraint-layout/motionlayout">Android Developers Guide on MotionLayout</a>.</p><h3>The Animation</h3><p>All the animations put together, the motion scene file for this project contains <strong>10 ConstraintSets </strong>and <strong>9 Transitions </strong>between them. The video below demonstrates all the ConstraintSets and Transitions. There are <strong>4 Animations</strong> in total that we will be looking into:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*a6zN5iGhjNuehrCNi6gwBw.gif" /></figure><ol><li><strong>Opening the filter sheet:<br></strong>Set1 → Set2 → Set3 → Set4</li><li><strong>Closing the filter sheet:<br></strong>Set4 → Set3 → Set2 → Set1</li><li><strong>Applying filters:<br></strong>Set4 → Set5 → Set6 → Set7</li><li><strong>Removing filters:<br></strong>Set7 → Set8 → Set9 → Set10</li></ol><p><strong><em>Note:</em></strong><em> The RecyclerView Items animation in the background is not a part of the MotionLayout. Later in this post, we will see how we can choreograph external animations along with the MotionLayout.</em></p><blockquote>Every animation (GIF) in this article will show the ConstraintSet details (Ex: Set 4, Transitioning.., Set 5, etc) below it to make it easier to follow while reading and navigating the source code.</blockquote><h3>&lt; ConstraintSet /&gt;</h3><p>ConstraintSets are the <em>building blocks</em> required by MotionLayout to perform animations. This is where you specify all your constraints, layout properties and more.</p><blockquote>A &lt;ConstraintSet&gt; must contain a &lt;Constraint&gt; element with all the layout properties <strong>for each view</strong> you want to animate.</blockquote><h4>Break up your &lt;Constraint&gt; elements</h4><p>You can specify all your layout properties in the &lt;Constraint&gt; element. <strong>But</strong> for more complex animations, you should break it up using the &lt;Layout&gt; &lt;PropertySet&gt; &lt;Transform&gt; &lt;Motion&gt; &lt;CustomAttribute&gt; tags.</p><p>This allows you to only override the properties that you want without rewriting all the properties repeatedly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P5OuFMZvsxccOKl5lgSqQg.png" /></figure><h4>app:deriveConstraintsFrom = ”…”</h4><p>deriveConstraintsFrom is a very useful tag that allows you to inherit from any other &lt;ConstraintSet&gt;. This way, you don’t have to rewrite all your views/constraints/properties but just the ones you want to animate.</p><p>Combine this with the previous tip of breaking up your &lt;Constraint&gt; elements and you get neat ConstraintSets with just the changes you want.</p><p>In this project, each of the 10 ConstraintSets derives from the previous set and only modifies what needs to be animated. For example: In the following transition, the close icon rotation is done by deriving all constraints from Set5 and only applying rotation in Set6.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_PKoZ0I_4Aj2adGSteJUbg.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BXjOwJORltd3n5o2cGqKJg.png" /></figure><blockquote><strong>Warning:</strong> When overriding one of the <em>&lt;Layout&gt; &lt;PropertySet&gt; &lt;Transform&gt; &lt;Motion&gt; &lt;CustomAttribute&gt;</em> elements, all the properties in that element get overriden, so you may have to copy the other properties from that element.</blockquote><h4>Flatten your views when necessary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*AuTuPGoxdr0YyejvJ733Dw.gif" /></figure><p>MotionLayout can only work with it’s <strong>direct children views</strong> and no nested views.</p><p>For example, in this animation, it may look like the filter icon is a part of the circular FAB (CardView). But they were split into separate views because they each have their own journey in this animation.</p><p>Also, the elevation of the fab is animated from Set1 → Set2. The icon must be placed at a higher elevation for it to be visible. An undesired effect of this is the icon casts it’s own shadow. To prevent this, we can use:</p><pre>android:outlineProvider=&quot;none&quot;</pre><p>Shadows are created by the outline provider of a view. If we set it to none then a shadow isn’t created.</p><h4>Custom Attributes</h4><p>MotionLayout provides most of the basic properties that we might want to animate. But it can’t provide <em>everything</em>. Custom Views, for example, might require animating some other property.</p><p>&lt;<a href="https://developer.android.com/reference/android/support/constraint/motion/MotionLayout#customattribute">CustomAttribute</a>&gt; bridges that gap by allowing you to use any <strong>setter</strong> in your view. It uses reflection to call the method and set the value.</p><pre>&lt;CustomAttribute <br>    app:attributeName=&quot;radius&quot;<br>    app:customDimension=&quot;16dp&quot; /&gt;</pre><blockquote><strong>Note:</strong> You must use the setter name, <strong>not</strong> the xml attr name. For example, CardView has a setRadius() method and the same in xml is app:cardCornerRadius. CustomAttribute should refer to the setter — “radius”.</blockquote><h4>“Invisible” vs “Gone”</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*ylmvRB33KyE_nQAy1Z3FPQ.gif" /><figcaption><strong>Left</strong>: invisible → visible ... <strong>Right</strong>: gone → visible</figcaption></figure><p>When animating visibility from invisible /gone to visible, watch out for this difference.</p><p><strong>✓ </strong>gone → visible will animate <strong>alpha and scale</strong>.</p><p><strong>✓</strong> invisible → visible will animate <strong>only alpha</strong>.</p><h3>&lt;Transition /&gt;</h3><p>Transitions are the connections between 2 ConstraintSets. They specify the start and end states to <em>transition</em> between.</p><pre>&lt;Transition<br>    app:constraintSetStart=&quot;@id/set1&quot;<br>    app:constraintSetEnd=&quot;@id/set2&quot;<br>    app:motionInterpolator=&quot;linear&quot;<br>    app:duration=&quot;300&quot; /&gt;</pre><p>You can also specify swipe and click related functionality in the transitions using the&lt;OnClick&gt; and &lt;OnSwipe&gt; elements but <strong>we will not be going into them in this article</strong> since they’re not rquired for the 10 set animation we’re looking at.</p><h4>Interpolators</h4><p>We can specify interpolators for our transitions using app:motionInterpolator. The available options are linear, easeIn, easeOut and easeInOut. These may not be enough when you compare them to things like <a href="https://developer.android.com/reference/android/view/animation/AnticipateInterpolator">AnticipateInterpolator</a>, <a href="https://developer.android.com/reference/android/view/animation/BounceInterpolator">BounceInterpolator</a>, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*CvYt6_vlb-Drn6usAGHAeA.png" /><figcaption><a href="https://cubic-bezier.com/#0,1,.5,1">https://cubic-bezier.com/#0,1,.5,1</a></figcaption></figure><p>For these scenarios, you can use the cubic() option where you can define your own interpolator using <strong>bezier curves</strong>. You can make your own bezier curves and get the values at <a href="https://cubic-bezier.com/">cubic-bezier.com</a>.</p><p>You can set it by using:<br>app:motionInterpolator=”cubic(0,1,0.5,1)</p><h4>Keyframes</h4><p>Sometimes, just having a start and end state isn’t enough. For more complex animations, we might want to specify the course of the transition in more detail. Keyframes help us specify <em>“checkpoints” </em>in the transition where we can change any attribute of a view at any given time.</p><p>The article “<a href="https://medium.com/google-developers/defining-motion-paths-in-motionlayout-6095b874d37">Defining motion paths in MotionLayout</a>” goes into more depth on keyframes and how to use them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*iHhkXoHN9Yg9TPO488G_LQ.gif" /><figcaption><strong>Left</strong>: With keyframes … <strong>Right</strong>: Without keyframes</figcaption></figure><p>The animation on the left is with <strong>9 keyframes</strong> and the one on the right is without keyframes.</p><p>As you can see, the start (set 4) and the end (set 5) are the same for both of them. But by using keyframes, we have much finer control on what happens to each element at any point during the transition.</p><h4>Structuring Keyframes</h4><p>Every &lt;Transition /&gt; can have one or more &lt;KeyFrameSet /&gt; elements in which all the keyframes are specified. For this project, only &lt;KeyPosition /&gt; and &lt;KeyAttribute /&gt; elements were used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GG0V6txfOjGmkWBvGgM-7w.png" /></figure><ul><li>motionTarget specifies which view is affected by the keyframe.</li><li>framePosition specifies when the keyframe is applied during the transition (0–100)</li><li>&lt;KeyPosition /&gt; is used to specify changes in width, height and x,y coordinates</li><li>&lt;KeyAttribute /&gt; is used to specify any other change <strong>including</strong> <strong>CustomAttributes</strong>.</li></ul><h4>framePosition = 0 vs 1</h4><p>Sometimes, we want to change a property at the <strong>very start</strong> of an animation. In normal animations, it is possible by using animator.doOnStart{...} or something similar. Let’s try achieving the same with keyframes..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*qdGFGc27RyXN0Q5rf86DqQ.gif" /><figcaption><strong>Left</strong>: framePosition=1 … <strong>Right</strong>: framePosition=0</figcaption></figure><p>In this particular animation, when the user clicks on the filter button, the animation begins by changing the fab (CardView) to a circle and collapsing it in size.</p><p>The problem here is when framePosition = 0 is used to alter the value at the start of the animation, MotionLayout doesn’t record it.</p><p>So, if you want to have a keyframe that specifies something at the start of any transition, use framePosition = 1 instead.</p><pre>&lt;KeyAttribute<br>    app:motionTarget=&quot;@id/fab&quot;<br>    app:framePosition=&quot;1&quot;&gt;<br>    &lt;CustomAttribute<br>        app:attributeName=&quot;radius&quot;<br>        app:customDimension=&quot;600dp&quot; /&gt;<br>&lt;/KeyAttribute&gt;</pre><h4>Use Custom Views when necessary</h4><p>The availability of CustomAttributes allows us to have flexible layouts with custom views.</p><p>For instance, a lot of the transitions in this animation involves the FAB (CardView) to grow and shrink <strong>as a circle</strong>. The issue with this is, to keep the CardView as a circle, cornerRadius must be &lt;= size/2. Normally this is easy with something like ValueAnimator because we know all the values at all times.</p><p>But MotionLayout hides all the calculations away from us. So to achieve this, we must introduce a new view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TP1JjqYD_Xb0qaylEulQDQ.png" /></figure><p>CircleCardView handles this case by limiting the radius to a max of size/2. Now when MotionLayout calls into the setter (remember CustomAttributes?), we won’t face any issues.</p><h3>Choreographing multi-step animations</h3><p>Currently, MotionLayout does not have an API that allows for controlled multi-step transitions. We can use autoTransition but it’s quite limiting (we’ll get into that later). In pseudocode, this is how you would do it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c6ef5833fdc911763bd19f085636883/href">https://medium.com/media/7c6ef5833fdc911763bd19f085636883/href</a></iframe><p>This quickly turns ugly and into the dreaded callback-hell. <strong>Coroutines</strong>, on the other hand help us convert asynchoronous callback code into linear code.</p><h4>MotionLayout.awaitTransitionComplete()</h4><p>Chris Banes’s article on <a href="https://medium.com/androiddevelopers/suspending-over-views-example-260ce3dc9100">Suspending over Views</a> is a must-read on how you can implement coroutines in View-related code.</p><p><a href="https://medium.com/androiddevelopers/suspending-over-views-example-260ce3dc9100">Suspending over Views — Example</a></p><p>He introduces us to awaitTransitionComplete(), which is a <strong>suspend function</strong> that hides away all the listeners, making it easy to wait for a transition to be complete using coroutines:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFk2YDqAfkC_pCugcEg5Og.png" /></figure><blockquote><strong>Note:</strong> The awaitTransitionComplete() extension method uses a <a href="https://gist.github.com/chrisbanes/a7371683c224464bf6bda5a25491aee0">modified MotionLayout</a> which enables multiple listeners to be set as opposed to only one (<a href="https://issuetracker.google.com/issues/144714753">feature request</a>).</blockquote><h4>AutoTransition</h4><p>autoTransition is the easiest way to achieve multi-step transitions <strong>without coroutines</strong>. Let’s say we want to achieve the <strong>“Removing Filters”</strong> animation from Set7 → Set8 → Set9 → Set10.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*BzpK3fI5sfSSA_y4k4TiQw.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6zdUCilxhMIf6xBvIaHXxg.png" /></figure><p>Now, if we do motionLayout.transitionToState(set8), MotionLayout transitions from Set7 → Set8. When it reaches Set8, it <strong>automatically transitions</strong> to Set9. And similarly, to Set10.</p><blockquote>autoTransition will automatically execute the transition when MotionLayout reaches the ConstraintSet specified in constraintSetStart.</blockquote><h4>AutoTransition is not perfect</h4><p>If you watch the animation again, you will notice that there is an animation going on with the adapter items in the background. To accomplish these animations <strong>in parallel</strong> with the MotionLayout transitions, we will have to use coroutines. They cannot be timed correctly by only using autoTransition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b2986634dd970beaa6cd7f262517bb7/href">https://medium.com/media/1b2986634dd970beaa6cd7f262517bb7/href</a></iframe><blockquote>The lines marked with //Simultaneous occur in parallel with the transition that’s taking place.</blockquote><p>Since autoTransition doesn’t wait when jumping from one transition to the next, awaitTransitionComplete() only lets us know when the transition is complete. It <strong>does not </strong>actually wait at the end of the transition. Which is why, we use transitionToState() only once, at the beginning.</p><h3>Multi-Step Forward and Reverse Transitions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*qB9qCBsilZrracH7BSGYHg.gif" /></figure><p>AutoTransition combined with coroutines help us achieve control over multi-step transitions.</p><p>But what if we want to animate backwards (Set4 → Set1) while reversing through each transition?</p><p>Reversing <strong>a specific </strong>transition, say, Set4 → Set3 is possible by using transitionToStart(). But if we use autoTransition, then it would animate to Set3, then back to Set4 <strong>automatically</strong> because of the autoTransition.</p><h4>Opening Sheet Animation</h4><p>The code for opening the filter sheet will differ slightly from what we saw in the previous section since we aren’t using autoTransition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5334b5f1f3cf39db3c02ca9a1e17aeb/href">https://medium.com/media/a5334b5f1f3cf39db3c02ca9a1e17aeb/href</a></iframe><ul><li>We have to use transitionToState() after awaiting each time. This was not necessary before because autoTransition would just run through all of them without waiting. Here, we have to do it manually.</li><li>Notice how we don’t use setTransition() everytime after awaiting. This is because MotionLayout will identify which transition to use based on the current ConstraintSet and the ConstraintSet mentioned in transitionToState().</li></ul><h4>Closing Sheet Animation (Reverse)</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/323acefb07e1f294f24d32936dc5288a/href">https://medium.com/media/323acefb07e1f294f24d32936dc5288a/href</a></iframe><p>Since all &lt;Transition&gt; elements are forward-based, we have to add a couple of lines to make it reverse-able. The essence of it is:</p><pre><strong>// Set the transition to be reversed (MotionLayout can only detect forward transitions).</strong><br>motionLayout.setTransition(startSet, endSet)</pre><pre><strong>// This will set the progress of the transition to the end</strong><br>motionLayout.progress = 1f</pre><pre><strong>// Reverse the transition from end to start</strong><br>motionLayout.transitionToStart()</pre><pre><strong>// Wait for transition to reach the start</strong><br>motionLayout.awaitTransitionComplete(startSet)</pre><pre><strong>// Repeat for every transition...</strong></pre><p>✔️ This now allows us to step through multiple transitions in reverse while maintaing the ability to do other things in parallel.</p><h3>Conclusion — With or without MotionLayout?</h3><p>MotionLayout combined with coroutines makes it super easy to achieve very complex animations with very little code <strong>while maintaing a flat view hierarchy!</strong></p><p><a href="https://proandroiddev.com/complex-ui-animation-on-android-8f7a46f4aec4">Complex UI/Animation on Android</a></p><p>In my <a href="https://proandroiddev.com/complex-ui-animation-on-android-8f7a46f4aec4?source=friends_link&amp;sk=f1fab1861a655b042ff5e9c305a0e012">previous article</a>, I explore how all of this was done <strong>without using MotionLayout. </strong>The amount of code required to get all this to work was much greater. A lot of math was involved in getting the animations to work, complex view hierarchies, etc.</p><blockquote>MotionLayout takes away all the nonsense and leaves us with what’s necessary. With coroutines and a soon-to-come IDE editor, the possibilities might just be endless.</blockquote><p>Hope you enjoyed this post 😃! Check out the <a href="https://github.com/nikhilpanju/FabFilter">source code</a> if you’re further interested!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa82d83b8660" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/complex-ui-animations-on-android-featuring-motionlayout-aa82d83b8660">Complex UI/Animations on Android — featuring MotionLayout</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Complex UI/Animation on Android]]></title>
            <link>https://proandroiddev.com/complex-ui-animation-on-android-8f7a46f4aec4?source=rss-f3034e2b0e9d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7a46f4aec4</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[motionlayout]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Nikhil Panju]]></dc:creator>
            <pubDate>Fri, 06 Dec 2019 17:46:07 GMT</pubDate>
            <atom:updated>2020-01-30T19:19:14.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gJtFxN4NGrKyg0HyPqlV6A.png" /></figure><h3>Complex UI/Animations on Android</h3><iframe src="https://cdn.embedly.com/widgets/media.html?url=https%3A%2F%2Fgfycat.com%2Fhairywellworngelding&amp;src=https%3A%2F%2Fgfycat.com%2Fifr%2Fhairywellworngelding&amp;type=text%2Fhtml&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;schema=gfycat" width="1280" height="1280" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fcaa733b17ed55a98c37dc89f6ebd7a/href">https://medium.com/media/4fcaa733b17ed55a98c37dc89f6ebd7a/href</a></iframe><h3>Before we begin</h3><ul><li>UX/UI Credit goes to Yaroslav Zubko. You can find the design <a href="https://dribbble.com/shots/2940944--5-Filters">here</a>.</li><li><strong>TLDR? View the </strong><a href="https://github.com/nikhilpanju/FabFilter"><strong>code</strong></a><strong> on Github or get the app on the </strong><a href="https://play.google.com/store/apps/details?id=com.nikhilpanju.fabfilter"><strong>PlayStore</strong></a><strong>.</strong></li><li>All parts of the animations were done via code (Kotlin). No XML animations/transitions were used because it would split up the animation code all over the place.</li><li><strong>This article doesn’t use </strong>MotionLayout because I wanted to try and achieve this by using Android animation fundamentals. The next article talks about doing the same by only using MotionLayout. Reading both offers a comprehensive comparison between both the methods.</li></ul><p><a href="https://medium.com/@nikhilpanju22/complex-ui-animations-on-android-featuring-motionlayout-aa82d83b8660">Complex UI/Animations on Android — featuring MotionLayout</a></p><h3>Let’s get into it..</h3><p>For most animations, I tend to use <a href="https://developer.android.com/reference/android/animation/ValueAnimator.html#ofFloat(float...)">ValueAnimator.ofFloat()</a> that animates from 0f to 1f (forward) / 1f to 0f (reverse). We can animate everything based on the progress between 0f and 1f. Here’s a simple top-level function that I use to make things easier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fefa4887a9b447753a00802924c1ae47/href">https://medium.com/media/fefa4887a9b447753a00802924c1ae47/href</a></iframe><h3>1. Toolbar Animation when scrolling</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*tEol1U0h_IY1oZWJEKVzIA.gif" /></figure><p>This toolbar animation was done using a custom CoordinatorLayout Behavior. There are many resources on how this can be done. Here’s the shortened code</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/275f2719b13ab0767d34829d977f0fd1/href">https://medium.com/media/275f2719b13ab0767d34829d977f0fd1/href</a></iframe><p>The important part is the onNestedScroll method where we use dyConsumed and dYUnconsumed to shrink and expand the toolbar accordingly.</p><p>This is how we set it to the <strong>appbar </strong>view in the activity:</p><pre>(appbar.layoutParams <strong>as </strong>CoordinatorLayout.LayoutParams).behavior = ToolbarBehavior()</pre><h3>2. RecyclerView Item Expand/Collapse Animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/240/1*aHxn2_CkzZTB-Cr-hgJU_g.gif" /></figure><p>To perform this animation, we need to calculate the original and expanded height. Since the view has it’s height set to wrap_content<em>, </em>we need to calculate the heights programatically (in onBindViewHolder). <strong>Usually, the height of a view with <em>wrap_content </em>is set after the view has been laid out.</strong> We can use these extensions from the ktx library to help us.</p><pre>View.doOnLayout{view -&gt; /* ... */}<br>View.doOnNextLayout{view -&gt; /* ... */}</pre><p>By using that, we can get originalHeight. For expandedHeight, we need to immediately make expandView<strong><em> </em></strong>(ViewGroup that contains all the expanded views) visible, measure the expandedHeight on the next layout and hide it again. All this happens in one layout pass, so it’s <em>practically</em> invisible to the user’s eyes <em>(If the heights are hardcoded values, then this step can be skipped).</em></p><p>Note: After writing this article, I realised doOnPreDraw{..} is better for this scenario. <a href="https://medium.com/@nikhilpanju22/good-question-the-answer-is-a-bit-mysterious-though-8a71a10f692f">Read this comment to know more.</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88569b6a2900da3e417a5b85ac029136/href">https://medium.com/media/88569b6a2900da3e417a5b85ac029136/href</a></iframe><p>Once we have the heights and the widths, animating the view is simple. Here’s a sample of the expandItem() method from the RecyclerView Adapter. Calling this when an item is clicked, expands/collapses the view based on the expand variable.</p><blockquote>When animating the width/height of a view using layoutParams, don’t forget to call requestLayout().</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c29de1cba5a3380848094ea2b2f7535d/href">https://medium.com/media/c29de1cba5a3380848094ea2b2f7535d/href</a></iframe><p>Using a variable like expandedModel to track which item is expanded, we can decide whether to collapse/expand the item. But how do we simultaneously expand one item and collapse another? (Look at animation above).</p><p>We can use recyclerView.findViewHolderForAdapterPosition() to get the expanded viewholder and collapse it. At the same time, we can expand the clicked item.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da55610d9c529b4e065b6a55d5b09565/href">https://medium.com/media/da55610d9c529b4e065b6a55d5b09565/href</a></iframe><h3>3. Tabs Scrolling Animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*tYVXzNsUqYLTu8IkZ7YnyQ.gif" /></figure><p>The tabs section is a RecyclerView that is in sync with the ViewPager2 below it. It also has a transformation applied to the <strong><em>active </em></strong>item similar to a ViewPager transformation. There are 2 things to consider:</p><h4><strong>#1 Scrolling the Tabs RecyclerView as the ViewPager is scrolled:</strong></h4><p>ViewPager2&#39;s onPageScrolled callback has position<strong><em> </em></strong>and positionOffset variables which determine the absolute scroll position of the ViewPager. Unfortunately, RecyclerView does not deal with absolute values since it <em>recycles</em> views and doesn’t know about off-screen views. It doesn’t implement the <em>absolute </em>scrollTo(x,y) method but has the <em>relative </em>scrollBy(x,y) method.</p><p>Since the number of tabs and the width of each tab item are fixed here, we use totalTabsScroll to keep track of the absolute total scroll position using RecyclerView’s OnScrollListener() callback. This allows us to convert absolute values to relative values and use scrollBy().</p><h4>#2 Transforming the current RecyclerView Item</h4><p>To transform the current item (scale up and fade color), we need absolute values. Since the ViewPager2 callback already gives us these, we can directly create a pseudo-transformer for the RecyclerView here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a048a1cdc15c18f9874617227047b77/href">https://medium.com/media/7a048a1cdc15c18f9874617227047b77/href</a></iframe><p>There are a couple of minor issues with this approach:</p><ol><li>Since the transformation happens from the ViewPager2<em> </em>callback and not the<em> </em>RecyclerView OnScrollListener, the transformation won’t work when the RecyclerView<em> </em>is scrolled by the user. Ideally, we can solve this by doing the transformation caluclation in the OnScrollListener<em> </em>but I decided to disable scrolling altogether and only enable clicks.</li><li>Disabling scrolling in the <em>LayoutManager </em>is not good because it stops programatic scrolling using scrollBy() as well. We can solve this by using a custom RecyclerView and LayoutManager:</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/816f677dbccf18f1d8ca20e37f9b0821/href">https://medium.com/media/816f677dbccf18f1d8ca20e37f9b0821/href</a></iframe><h3>4. Filter Sheet Open/Close Animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*QVe7s8A-yuuES9qoACQfgQ.gif" /></figure><p>This animation consists of 4 sections:</p><ol><li>Floating Action Button (FAB) <strong>arc path animation</strong> where the button moves to the centre of the screen.</li><li><strong>Scale Down Animation</strong> which shrinks and fades all the RecyclerView items in the background.</li><li><strong>FAB Reveal Animation</strong> where the button circular reveals into a bottom sheet while the filter icon moves down.</li><li><strong>Elements Settle Animation</strong> where the tabs slide up, viewpager fades in and the bottom bar slides and fades in.</li></ol><p>The FAB is actually just a CardView. <strong>For a lot of the animations the </strong><a href="https://github.com/nikhilpanju/FabFilter/blob/master/app/src/main/java/com/nikhilpanju/fabfilter/utils/CardViewAnimatorHelper.kt">CardViewAnimatorHelper</a> <strong>helper class is used.</strong> It provides a ValueAnimator making it easy to animate CardView attributes like elevation, radius, etc.</p><h4>#1 FAB Arc Path Animation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*So-Ng5izk9JcMd_G1EKFDQ.gif" /></figure><p>CardViewAnimatorHelper is all we need for this animation. Supplying isArcPath = true takes care of arcing the path. Internally it uses <a href="https://github.com/asyl/ArcAnimator">ArcAnimator</a> to get arc path values.</p><pre><strong>val </strong>pathAnimator = CardViewAnimatorHelper(<br>        cardView = fab,<br>        startX = fabX, startY = fabY,<br>        endX = fabX2, endY = fabY2,<br>        startElevation = fabElevation, endElevation = fabElevation2,<br>        isArcPath = <strong>true</strong>,<br>        duration = pathAnimDuration,<br>        interpolator = pathAnimInterpolator<br>).getAnimator(isOpening)</pre><h4>#2 Scale Down Animation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*jNxBF2_PQ8wOuukJ3Xb54w.gif" /></figure><p>All the RecyclerView items fade and <em>scale down </em>in the background as the arc path happens. To do this, we need to animate all the visible items in the LayoutManager. In the RecyclerView Adapter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8947320544e8cdc9f4b422f86792cc8d/href">https://medium.com/media/8947320544e8cdc9f4b422f86792cc8d/href</a></iframe><h4>#3 Reveal Animation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*ToxiAQi89AtbO0eP2yS7BQ.gif" /></figure><p>This reveal animation <strong>does not</strong> use the Android Utils <a href="https://developer.android.com/reference/android/view/ViewAnimationUtils.html">Circular Reveal</a> because the filter icon needs to translate down simultaneously. We can do this by setting layout_gravity = bottom|center_horizontal to the icon in the CardView and calling requestLayout() when animating the CardView. Also, you may have noticed, the reveal is not a perfect circular reveal. It’s an increase in circle size of the CardView followed by un-curving the corners (radius = 0).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd6dbb0ad97b368c37a7b5c4dc1f56a3/href">https://medium.com/media/cd6dbb0ad97b368c37a7b5c4dc1f56a3/href</a></iframe><p><a href="https://github.com/nikhilpanju/FabFilter/blob/master/app/src/main/java/com/nikhilpanju/fabfilter/utils/CardViewAnimatorHelper.kt">CardViewAnimatorHelper</a> can fetch you an animator using getAnimator() directly or you can set progress to it for manual control. We use the latter method here.</p><h4><em>#4</em> Settle Animation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/280/1*E6wfjstdZ872d0wn056vYg.gif" /></figure><p>This animation is nothing special. It’s just views fading, sliding and <em>settling</em> in. <strong>But what’s interesting is</strong>, although it may seem fluid coming off of the reveal animation, it isn’t. <br>The reveal animation was done on the fab CardView. But once the reveal is done, another ViewGroup main_container which has a <strong>higher elevation</strong> than the fab is made visible and the settle animation happens on the elements in that ViewGroup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6401fd9480fb873ad7655d3fece4ac3/href">https://medium.com/media/d6401fd9480fb873ad7655d3fece4ac3/href</a></iframe><p>After the reveal animation, main_container is made visible and picks up the animation from there. The reverse is done when closing the filter sheet. This was done because if all the elements were in the fab CardView, it’s not easy to animate them considering how the fab grows and shrinks in size (*cough* MotionLayout *cough*).</p><pre><strong>if </strong>(isOpening) revealAnimator.<em>doOnEnd </em><strong>{ </strong>mainContainer.<em>isVisible </em>= <strong>true }<br>else </strong>revealAnimator.<em>doOnStart </em><strong>{ </strong>mainContainer.<em>isVisible </em>= <strong>false }</strong></pre><p>Note that the bottom bar is a separate CardView. The fab and the bottom bar being separate CardViews helps with the next animation (explained soon).</p><h4>Choroeographing animation with AnimatorSet</h4><p>I’m not too fond of the AnimatorSet API because of some of it’s gotchas and <a href="https://medium.com/@nikhilpanju22/great-article-eb5862894a9c">other reasons</a>. (Check out <a href="https://medium.com/u/9303277cb6db">Chris Banes</a>’s post on using coroutines with animators). But here’s how it’s done for this animation:</p><pre><strong>val </strong>set = AnimatorSet()<br><strong>if </strong>(isOpening) {<br>    set.play(pathAnimator).with(scaleDownAnimator)<br>    set.play(pathAnimator).before(revealAnimator)<br>    set.play(revealAnimator).before(settleAnimator)<br>} <strong>else </strong>{<br>    set.play(settleAnimator).before(revealAnimator)<br>    set.play(revealAnimator).before(pathAnimator)<br>    set.play(pathAnimator).with(scaleDownAnimator)<strong><br></strong>}<br>set.start()</pre><h3>Filtering Animation</h3><p>This animation consists of 6 animations. We will not be going into too much detail for this one as these animations mostly use CardViewHelperAnimator, CircleCardViewHelperAnimator and other concepts explained before. The <a href="https://github.com/nikhilpanju/FabFilter/blob/master/app/src/main/java/com/nikhilpanju/fabfilter/filter/FiltersLayout.kt">source code</a> is well documented for every step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*_nU7fDoJ16zgKG_2o7_cmg.gif" /></figure><ol><li><strong>Fab Collapse Animation.</strong> The fab collapses to it’s original size.</li><li><strong>Bottom Bar Animation.</strong> The bottom bar translates and collapses into the fab while centering the close icon and fading out the filter icon.</li><li>Tabs and Viewpager <strong>fade out animation</strong>.</li><li><strong>Close Icon rotate animation</strong> to simulate loading.</li><li><strong>Fab Arc Path Animation</strong></li><li>RecyclerView items <strong>scale down animation</strong>.</li></ol><p>As mentioned before, having the fab, filter sheet and bottom bar as separate views helps us achieve this animation because each of them can be controlled separately. The bottom bar is a separate cardview for the sole purpose of being able to animate corner radius easily to turn into a circle.</p><p><strong>#1 Fab Collapse Animation</strong> grows the fab slightly before collapsing. This is done using an <a href="https://developer.android.com/reference/android/view/animation/AnticipateInterpolator">AnticipateInterpolator</a>. The animation itself is done using <a href="https://github.com/nikhilpanju/FabFilter/blob/master/app/src/main/java/com/nikhilpanju/fabfilter/utils/CardViewAnimatorHelper.kt">CircleCardViewHelperAnimator</a>.</p><p><strong>#2 Bottom Bar Animation</strong> turns the bottom bar into a small circle, inset into the fab. This is also done using the helper class and supplying appropriate values. Additionaly, the close icon is translated to the middle of the circle and the filter icon is faded out.</p><p><strong>#3 Tabs and ViewPager fade out</strong> (alpha and scale). Nothing special.</p><p><strong>The first 3 animations are done in parallel</strong>. At the end of it, main_container (containing filter sheet and bottom bar) is hidden and the rest of the animation takes place on the fab.<br>Note: The fab has a close icon that’s identical to the bottom bar inset end result so it’s seamless when transitioning.</p><p><strong>#4</strong> <strong>Close Icon is rotated</strong> on the fab while the RecyclerView in the backgroud is filtered. RecyclerView Item Animation duration can be adjusted:</p><pre>recyclerView.itemAnimator?.<em>removeDuration </em>= duration<br>recyclerView.<em>itemAnimator</em>?.<em>addDuration </em>= duration</pre><p><strong>#5</strong> Fab Arc Path and <strong>#6</strong> RecyclerView scale down animations are explained earlier. It’s the exact same.</p><p>AnimatorSet is used to choreograph the animation in this order:<br>(1,2,3) together, then 4, then (5, 6) together</p><h3>Clearing Filters Animation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*EnizAePWDd3BVO1u1RcGgg.gif" /></figure><p>This is the last animation. It clears all the filters while animating the fab. This involves concepts already explained before so we will not be breaking this down.</p><h3>Conclusion</h3><p>A lot of these animations may not be practical but this post was written mainly because a lot of the concepts here are quite useful.</p><p>MotionLayout makes a lot of this much easier. If you want to know more, read my next article on how I achieved all the same animations here by only using MotionLayout.</p><p><a href="https://medium.com/@nikhilpanju22/complex-ui-animations-on-android-featuring-motionlayout-aa82d83b8660">Complex UI/Animations on Android — featuring MotionLayout</a></p><p>Hope you enjoyed my <em>first</em> post here, on Medium 😃. Check out the <a href="https://github.com/nikhilpanju/FabFilter">source code</a> if you’re further interested!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7a46f4aec4" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/complex-ui-animation-on-android-8f7a46f4aec4">Complex UI/Animation on Android</a> was originally published in <a href="https://proandroiddev.com/">ProAndroidDev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>