<?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 Tanish on Medium]]></title>
        <description><![CDATA[Stories by Tanish on Medium]]></description>
        <link>https://medium.com/@tanish2k09?source=rss-d03a26f30a90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nir0pVHatU_0LkWgY8pZew@2x.jpeg</url>
            <title>Stories by Tanish on Medium</title>
            <link>https://medium.com/@tanish2k09?source=rss-d03a26f30a90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:44:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tanish2k09/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[Advanced custom Android Activity transitions inspired by shared elements]]></title>
            <link>https://medium.com/@tanish2k09/advanced-custom-android-activity-transitions-inspired-by-shared-elements-1ec5a76c27e8?source=rss-d03a26f30a90------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ec5a76c27e8</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[transitions]]></category>
            <dc:creator><![CDATA[Tanish]]></dc:creator>
            <pubDate>Sun, 02 Jul 2023 11:45:28 GMT</pubDate>
            <atom:updated>2023-11-22T02:23:52.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*GeD0b10uzEgVH8fSsojmQA.gif" /><figcaption>Source: <a href="https://m2.material.io/design/introduction">https://m2.material.io/design/introduction</a></figcaption></figure><h3><strong>Table of Contents</strong></h3><ol><li><a href="#8ee6"><strong>👋 Intro &amp; Examples</strong></a><strong><br>- </strong>Examples<br>- Preview of article demo</li><li><a href="#6de7"><strong>The issue with SharedElementTransition 💭</strong></a></li><li><a href="#fa63"><strong>Alright, let’s begin with Shake 👀</strong></a><strong><br>- </strong>Setup<br>- Shake Animation</li><li><a href="#dcaf"><strong>Adding a Splash-to-Login transition 🟢</strong></a></li><li><a href="#faa1"><strong>Adding a Login-to-Home transition 🔓🔑</strong></a></li><li><a href="#b8df"><strong>Parting notes + Demo source code 💻</strong></a></li></ol><h3><strong>👋 Intro &amp; Examples</strong></h3><p>One of the most incredible things you can do as a mobile developer is add fun and interactive animations and transitions to your app. <strong>But</strong> there’s a clear distinction between simple fades and the more shiny, eye-catching, dynamic UI transitions.</p><p>Here are some examples of such eye candy:</p><figure><img alt="A music player concept with the play FAB morphing into music controls" src="https://cdn-images-1.medium.com/max/800/0*f1N71SbmKN6r6XY_.gif" /><figcaption><a href="https://dribbble.com/shots/2101776-Material-Design-The-Morphing-FAB">The Morphing FAB — Google</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*ugAjN87UAqJvgPZ_.gif" /><figcaption><a href="https://github.com/Cuberto/liquid-swipe">Liquid Swipe — Cuberto</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*55hwSFgBtEw9hRxt.gif" /><figcaption><a href="https://github.com/Cuberto/smooth-scroll">Smooth Scroll — Cuberto</a></figcaption></figure><p>Here’s a preview of what this article aims to achieve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*UzBNFrd3P_EOpL928TeLmA.gif" /><figcaption>hubSFU — A quick project my team created in a hackathon</figcaption></figure><p>For this tutorial, we’re only concerned about the cross-activity transitions using a common element (the red button), so to keep things simple, we will use a very simple layout to start off and focus on the actual transitions. The idea here is to give you a hint at unleashing your creative potential within your transitions — and hopefully, by the end, you’ll already be thinking of UI elements to animate.</p><blockquote>Note: This guide uses min-sdk level 28 (Pie)</blockquote><h3>The issue with SharedElementTransition 💭</h3><p>I’d like to mention that SharedElementTransition is an amazing and extremely convenient transition tool available in android and takes care of nearly all of the long and complex animation code. However, this comes at the cost of customization — there’s only so many pre-defined options available. The good thing is they cover possibly 99% of the use cases, but the bad thing is that you can’t specify custom movement paths or view transition behaviours. Ideally the API evolves to provide callbacks on the progress of the transition so that a custom class can handle how to morph the views. Until that happens, we’re stuck with making complex custom transitions the old-fashioned way.</p><p>SharedElementTransition seems to use ViewOverlay under-the-hood, which means views shared amongst Activity A -&gt; B are hidden from A and added to B in a ViewOverlay in the exact same positions and states, and then B interpolates from the received states of views to their final states.</p><p>Think of it like, A “hands over” information about the shared views, B receives the data, places its own views according to A’s data, and then animates the views based on B’s own layout data. This is a really clean technique and it clearly works.</p><p>However, in this guide we’re gonna use a technique where both activity A and B assume some knowledge of each other’s layout. A tries to manipulate its views in order to present a visual state that can be handed off to B. B then sets itself up according to this common visual state, and deconstructs it into its true layout. Take a look at the hubSFU gif, it might make more sense. The main idea here is to reach a common visual point that looks like it “connects” two activities.</p><h3>Alright, let’s begin with Shake 👀</h3><p>First off, we’re gonna add a login activity and set a transparent style to it. The parent style for this tutorial is .Light.NoActionBar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*wSqXakcsvXurPyU4eZ2-GA.png" /></figure><p>The transparent style isn’t necessary but looks more pleasant because the transitions can be drawn behind system bars. Don’t forget to set it to your login activity in the manifest!</p><pre>&lt;style name=&quot;Theme.Advancedandroidactivitytransition.PseudoFullScreen&quot; parent=&quot;Theme.Advancedandroidactivitytransition&quot;&gt;<br>    &lt;item name=&quot;android:windowTranslucentStatus&quot;&gt;true&lt;/item&gt;<br>    &lt;item name=&quot;android:windowTranslucentNavigation&quot;&gt;true&lt;/item&gt;<br>    &lt;item name=&quot;android:windowLightNavigationBar&quot;&gt;false&lt;/item&gt;<br>    &lt;item name=&quot;android:windowLightStatusBar&quot;&gt;false&lt;/item&gt;<br>&lt;/style&gt;</pre><p>If you choose to go the transparent activity route, you’re gonna need some helper functions to inset the content of the activity so they’re not drawn behind the system bars.</p><pre>// Name this file ActivityExtensions.kt or similar<br><br>fun fitWithinSystemBars(topView: View, marginTop: Int, bottomView: View, marginBottom: Int) {<br>    fitTopWithinSystemBars(topView, marginTop)<br>    fitBottomWithinSystemBars(bottomView, marginBottom)<br>}<br><br>fun fitTopWithinSystemBars(topView: View, marginTop: Int, consume: Boolean = true) {<br>    ViewCompat.setOnApplyWindowInsetsListener(topView) { view, windowInsets -&gt;<br>        val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())<br>        view.updateLayoutParams&lt;ViewGroup.MarginLayoutParams&gt; {<br>            topMargin = insets.top + marginTop<br>        }<br><br>        // Returning .CONSUMED means the inset change will not propagate on to subviews<br>        // This will be useful when changing insets for both a parent and a child<br>        if (consume) {<br>            WindowInsetsCompat.CONSUMED<br>        } else {<br>            windowInsets<br>        }<br>    }<br>}<br><br>fun fitBottomWithinSystemBars(bottomView: View, marginBottom: Int, consume: Boolean = true) {<br>    ViewCompat.setOnApplyWindowInsetsListener(bottomView) { view, windowInsets -&gt;<br>        val insets = windowInsets.getInsets(WindowInsetsCompat.Type.systemBars())<br>        view.updateLayoutParams&lt;ViewGroup.MarginLayoutParams&gt; {<br>            bottomMargin = insets.bottom + marginBottom<br>        }<br><br>        // Returning .CONSUMED means the inset change will not propagate on to subviews<br>        // This will be useful when changing insets for both a parent and a child<br>        if (consume) {<br>            WindowInsetsCompat.CONSUMED<br>        } else {<br>            windowInsets<br>        }<br>    }<br>}</pre><p>At this point, your login activity should have a username, password, login and loading views. We’re gonna set the username top margin to @dimen/login_margin_top and use fitTopWithinSystemBars() to make sure it stays in safe area (below status bar):</p><pre>&lt;EditText<br>        android:id=&quot;@+id/username&quot;<br>        ...<br>        android:layout_marginTop=&quot;@dimen/login_margin_top&quot; /&gt;</pre><pre>// In your LoginActivity.kt<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>    // ... other stuff<br><br>    fitTopWithinSystemBars(<br>            binding.username,<br>            resources.getDimensionPixelOffset(R.dimen.login_margin_top)<br>        )<br>}</pre><p>Next we’re gonna style our login button with rounded corners:</p><pre>&lt;Button<br>        android:id=&quot;@+id/login&quot;<br>        ...<br>        android:enabled=&quot;false&quot;<br>        android:background=&quot;@drawable/rounded_button&quot;<br>&gt;</pre><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;ripple xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; android:color=&quot;@color/white&quot;&gt;<br>    &lt;item&gt;<br>        &lt;selector&gt;<br>            &lt;item android:state_enabled=&quot;false&quot;&gt;<br>                &lt;shape android:shape=&quot;rectangle&quot;&gt;<br>                    &lt;corners android:radius=&quot;@dimen/login_button_corner&quot;/&gt; &lt;!-- 40dp --&gt;<br>                    &lt;solid android:color=&quot;@color/primary_disabled&quot; /&gt;<br>                &lt;/shape&gt;<br>            &lt;/item&gt;<br>            &lt;item&gt;<br>                &lt;shape android:shape=&quot;rectangle&quot;&gt;<br>                    &lt;corners android:radius=&quot;@dimen/login_button_corner&quot;/&gt;<br>                    &lt;solid android:color=&quot;@color/primary_color&quot; /&gt;<br>                &lt;/shape&gt;<br>            &lt;/item&gt;<br>        &lt;/selector&gt;<br>    &lt;/item&gt;<br>&lt;/ripple&gt;</pre><p>Let’s add the login button shake animation upon failed login. The animation code is provided below, but the logic to trigger a failed login is left to the reader. In the template provided by Android Studio currently, it is handled in LoginDataSource.kt</p><pre>// In LoginActivity.kt<br><br>private fun loginShakeAnimation() {<br>        // Make the button unclickable for the duration of the animation - also acts as a timeout<br>        binding.login.isClickable = false<br><br>        val shakeDuration = resources.getInteger(R.integer.login_button_fail_shake_duration).toLong()<br>        val resetDuration = resources.getInteger(R.integer.login_button_fail_reset_duration).toLong()<br><br>        // Idea from: https://stackoverflow.com/a/27943288/5475354<br>        val shakeXHolder = PropertyValuesHolder.ofFloat(View.TRANSLATION_X, 0f, 25f, -25f, 25f, -25f, 15f, -15f, 6f, -6f, 0f)<br>        val scaleXHolder = PropertyValuesHolder.ofFloat(View.SCALE_X, 1.1f)<br>        val scaleYHolder = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.1f)<br><br>        // Animation shaking horizontally, and scaling up the button in both XY together<br>        ObjectAnimator<br>            .ofPropertyValuesHolder(binding.login, shakeXHolder, scaleXHolder, scaleYHolder)<br>            .setDuration(shakeDuration)<br>            .start();<br>         <br>        // Reset the button scale in XY to 1f and then make button clickable again.<br>        val resetAnimatorSet = AnimatorSet()<br>        resetAnimatorSet.apply {<br>            playTogether(<br>                ObjectAnimator.ofFloat(binding.login, &quot;scaleX&quot;, 1f),<br>                ObjectAnimator.ofFloat(binding.login, &quot;scaleY&quot;, 1f)<br>            )<br>            interpolator = DecelerateInterpolator()<br>            duration = resetDuration<br>            startDelay = shakeDuration // Note how the delay is equal to the duration of the &quot;shake&quot;<br>            addListener(object : AnimatorListenerAdapter() {<br>                override fun onAnimationEnd(animation: Animator) {<br>                    binding.login.isClickable = true<br>                }<br>            })<br>            start()<br>        }<br>    }<br><br>// We update this method to trigger the animation instead of showing a toast<br>private fun showLoginFailed(@StringRes errorString: Int) {<br>    // Hide the keyboard<br>    getSystemService(Context.INPUT_METHOD_SERVICE)?.let {<br>        (it as InputMethodManager).hideSoftInputFromWindow(binding.root.windowToken, 0)<br>    }<br><br>    // Shake the login button<br>    loginShakeAnimation()<br>}</pre><pre>&lt;!-- res/values/integer.xml --&gt;<br><br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;resources&gt;<br>    &lt;integer name=&quot;login_button_fail_shake_duration&quot;&gt;500&lt;/integer&gt;<br>    &lt;integer name=&quot;login_button_fail_reset_duration&quot;&gt;250&lt;/integer&gt;<br>&lt;/resources&gt;</pre><p>If done correctly, you should have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*j8G86EDXjF1NyG_pNAg8XQ.gif" /><figcaption>Login button shake animation</figcaption></figure><h3>Adding the Splash-to-Login transition 🟢</h3><p>We’re gonna add another basic empty activity to act as our first-run onboarding splash screen. If you styled the LoginActivity transparent, you’d wanna keep it consistent in the other activities as well. I’m gonna name this SplashActivity and set its theme to .PseudoFullScreen</p><p>The way this transition works is by having a FAB in SplashActivity scale up to cover the entire screen, then using overridePendingTransition() to show LoginActivity again but with a UI state set up that looks like the full-screen FAB appearance — we achieve this by scaling the “Sign in” button to the entire screen instead.</p><p>Let’s set up the FAB in SplashActivity and write the “Circular ripple” animation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*kbVcYKgsznsemm5Ws0D3SQ.png" /><figcaption>activity_splash.xml</figcaption></figure><p>For the Ripple animation, we want the FAB to fade the FAB icon/drawable, then translate up towards the center of the screen, whilst shrinking in scale and then exploding in scale to cover the entire screen. I’m gonna do it in code instead of XML animator resources because of the screen size calculations involved. Here’s how we do it in SplashActivity.kt:</p><pre>&lt;!-- We&#39;re gonna add some resource values first: --&gt;<br><br>&lt;!-- dimens.xml - bottom margin of textView in SplashActivity --&gt;<br>&lt;dimen name=&quot;splash_margin_bottom&quot;&gt;32dp&lt;/dimen&gt;<br><br>&lt;!-- integer.xml - timing values for the animation (milliseconds) --&gt;<br>&lt;integer name=&quot;fab_ripple_explode_duration&quot;&gt;500&lt;/integer&gt;<br>&lt;integer name=&quot;fab_ripple_scale_down_duration&quot;&gt;500&lt;/integer&gt;<br>&lt;integer name=&quot;fab_ripple_scale_down_factor&quot;&gt;4&lt;/integer&gt;<br>&lt;integer name=&quot;fab_ripple_translate_duration&quot;&gt;1000&lt;/integer&gt;<br>&lt;integer name=&quot;fab_ripple_icon_fade_duration&quot;&gt;200&lt;/integer&gt;<br></pre><pre>// SplashActivity.kt<br><br>private lateinit var binding: ActivitySplashBinding<br><br>// For SDK Level &lt; 30 - <br>// we keep a copy of this value and update it in attachListeners()<br>private var legacyDisplayHypotenuse: Float = 0f<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br><br>    // Standard view binding<br>    binding = ActivitySplashBinding.inflate(layoutInflater)<br>    setContentView(binding.root)<br><br>    // Make sure our textView isn&#39;t under the navbar<br>    fitBottomWithinSystemBars(<br>        binding.textView,<br>        resources.getDimensionPixelOffset(R.dimen.splash_margin_bottom)<br>    )<br>    attachListeners()<br>}<br><br>// You can choose to exit the app from splash screen, or ignore back presses.<br>override fun onBackPressed() {<br>    finishAffinity()<br>}</pre><pre>private fun attachListeners() {<br>    binding.floatingActionButton.setOnClickListener {<br>        // This is where the magic happens<br>        revealActivity()<br>    }<br><br>    // For SDK Level &lt; 30 - update legacy hypotenuse, used in animation.<br>    binding.root.setOnApplyWindowInsetsListener { _, insets -&gt;<br>        val displayMetrics = resources.displayMetrics<br>        val height =<br>            displayMetrics.heightPixels + insets.systemWindowInsetTop + insets.systemWindowInsetBottom<br>        val width =<br>            displayMetrics.widthPixels + insets.systemWindowInsetLeft + insets.systemWindowInsetRight<br>        legacyDisplayHypotenuse = hypot(width.toFloat(), height.toFloat())<br>        insets<br>    }<br>}</pre><pre>private fun getWindowHypotenuse(): Float {<br>    // The idea here is that to cover the full screen,<br>    // the radius of the FAB would have to be half of the diagonal of the screen<br>    // but displayMetrics doesn&#39;t include the size of system bars - which we need if our activity is transparent.<br>    // So we use WindowMetrics.getBounds() instead. https://developer.android.com/reference/android/view/WindowMetrics#getBounds()<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.R) {<br>        val bounds = windowManager.currentWindowMetrics.bounds<br>        return hypot(bounds.width().toFloat(), bounds.height().toFloat())<br>    }<br><br>    return legacyDisplayHypotenuse<br>}<br><br>// NOTE: We&#39;re also gonna use getWindowBottomInset() and getWindowInsetHeight()<br>// The implementation of these is straightforward and left up to the reader.</pre><pre>// Here&#39;s the actual animation of the FAB<br><br>private fun revealActivity() {<br>    // make FAB un-clickable<br>    binding.floatingActionButton.isClickable = false<br><br>    // Get durations from resources<br>    val translateDuration =<br>        resources.getInteger(R.integer.fab_ripple_translate_duration).toLong()<br>    val iconFadeDuration =<br>        resources.getInteger(R.integer.fab_ripple_icon_fade_duration).toLong()<br>    val scaleDownDuration =<br>        resources.getInteger(R.integer.fab_ripple_scale_down_duration).toLong()<br>    val explodeDuration = resources.getInteger(R.integer.fab_ripple_explode_duration).toLong()<br>    val fabScaleDownFactor =<br>        resources.getInteger(R.integer.fab_ripple_scale_down_factor).toFloat()<br><br>    // The idea here is that to cover the full screen,<br>    // the radius of the FAB would have to be half of the diagonal of the screen<br>    // but displayMetrics doesn&#39;t include the size of system bars - which we need if our activity is transparent.<br>    // So we use WindowMetrics.getBounds() instead. https://developer.android.com/reference/android/view/WindowMetrics#getBounds()<br>    val fabScaleUp = getWindowHypotenuse() * 2 / binding.floatingActionButton.height<br><br>    // Fade the FAB icon by changing transparency to 0<br>    ObjectAnimator.ofArgb(binding.floatingActionButton.drawable, &quot;alpha&quot;, 0).apply {<br>        duration = iconFadeDuration<br>        interpolator = AccelerateInterpolator()<br>        start()<br>    }<br><br>    // Move the FAB to the center of the screen<br>    val displayCenter =<br>        resources.displayMetrics.heightPixels / 2 - binding.floatingActionButton.height / 2<br>    ObjectAnimator.ofFloat(binding.floatingActionButton, View.Y, displayCenter.toFloat())<br>        .apply {<br>            duration = translateDuration<br>            interpolator = DecelerateInterpolator()<br>            startDelay = iconFadeDuration<br>            start()<br>        }<br><br>    // Shrink and then explode the FAB to fill the screen<br>    val shrinkXHolder = PropertyValuesHolder.ofFloat(View.SCALE_X, 1.0f / fabScaleDownFactor)<br>    val shrinkYHolder = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1.0f / fabScaleDownFactor)<br>    ObjectAnimator.ofPropertyValuesHolder(<br>        binding.floatingActionButton,<br>        shrinkXHolder,<br>        shrinkYHolder<br>    ).apply {<br>        duration = scaleDownDuration<br>        interpolator = DecelerateInterpolator()<br>        start()<br>    }<br><br>    val explodeXHolder = PropertyValuesHolder.ofFloat(View.SCALE_X, fabScaleUp)<br>    val explodeYHolder = PropertyValuesHolder.ofFloat(View.SCALE_Y, fabScaleUp)<br>    ObjectAnimator.ofPropertyValuesHolder(<br>        binding.floatingActionButton,<br>        explodeXHolder,<br>        explodeYHolder<br>    ).apply {<br>        duration = explodeDuration<br>        interpolator = AccelerateInterpolator()<br>        startDelay = scaleDownDuration<br>        addListener(object : AnimatorListenerAdapter() {<br>            override fun onAnimationEnd(animation: android.animation.Animator) {<br>                this@SplashActivity.finish()<br>                overridePendingTransition(0, 0)<br>            }<br>        })<br>        start()<br>    }<br>}</pre><p>Awesome, we got the animation set up for the FAB. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*qgzMse0Jwn_yGQPkXGOBIA.gif" /><figcaption>FAB exploding animation</figcaption></figure><p>Notice how the activity immediately disappears after the FAB ripple, thanks to overridePendingTransition(0, 0) — this will be extremely important because it allows us to directly “shift” the UI state to the next activity.</p><p>Next up, we’re gonna set up LoginActivity to set up its UI to seamlessly transition from SplashActivity&#39;s end. The idea here is to have the login button be fully scaled up to the screen with transparent text, and then animate a scale down, translate and a color shift (from FAB’s teal to login button’s disabled-gray), and color shift in the text (this basically works as a text fade, but the text within a Button has no way to change opacity besides changing the color — and it’s also simple enough)</p><p>We need some more timing values so let’s define it within integer.xml :</p><pre>&lt;integer name=&quot;splash_login_scale_duration&quot;&gt;1000&lt;/integer&gt;<br>&lt;integer name=&quot;splash_login_translate_delay&quot;&gt;100&lt;/integer&gt;<br>&lt;integer name=&quot;splash_login_translate_duration&quot;&gt;500&lt;/integer&gt;<br>&lt;integer name=&quot;splash_login_shift_duration&quot;&gt;1000&lt;/integer&gt;<br>&lt;integer name=&quot;splash_login_text_fade_duration&quot;&gt;500&lt;/integer&gt;<br>&lt;integer name=&quot;splash_login_text_fade_delay&quot;&gt;800&lt;/integer&gt;</pre><p>Let’s set up the initial state right after the “transition handover”:</p><pre>// LoginActivity.kt<br>// Note: getWindowHypotenuse and legacyDisplayHypotenuse were used here<br>// similar to SplashActivity<br><br>private fun setupViewsForSplashTransition() {<br>    // Make the login button vertically centered<br>    // Make the login button full-screen<br>    val transitionView = binding.login<br><br>    transitionView.post {<br>        transitionView.visibility = View.VISIBLE<br>        transitionView.isEnabled = false<br>        transitionView.isClickable = false<br>        transitionView.setTextColor(getColor(android.R.color.transparent))<br>        val centerY =<br>            resources.displayMetrics.heightPixels / 2 - transitionView.height / 2<br>        val fullScale = getWindowHypotenuse() / min(transitionView.height, transitionView.width)<br>        // Note: getWindowHypotenuse() is also used here so you may abstract it out of both activities<br><br>        transitionView.translationY = centerY - transitionView.y<br>        transitionView.scaleX = fullScale<br>        transitionView.scaleY = fullScale<br>    }<br>}</pre><p>…and now we can define the actual animation of the button:</p><pre>private fun transitionFromSplash() {<br>    val transitionView = binding.login<br>    val scaleDownDuration = resources.getInteger(R.integer.splash_login_scale_duration).toLong()<br>    val translateDuration = resources.getInteger(R.integer.splash_login_translate_duration).toLong()<br>    val translateDelay = resources.getInteger(R.integer.splash_login_translate_delay).toLong()<br>    val scaleXHolder = PropertyValuesHolder.ofFloat(View.SCALE_X, 1f)<br>    val scaleYHolder = PropertyValuesHolder.ofFloat(View.SCALE_Y, 1f)<br>    val translationYHolder = PropertyValuesHolder.ofFloat(View.TRANSLATION_Y, 0f)<br>    val shiftDuration = resources.getInteger(R.integer.splash_login_shift_duration).toLong()<br>    val textFadeDuration = resources.getInteger(R.integer.splash_login_text_fade_duration).toLong()<br>    val textFadeDelay = resources.getInteger(R.integer.splash_login_text_fade_delay).toLong()<br><br>    ObjectAnimator.ofPropertyValuesHolder(transitionView, scaleXHolder, scaleYHolder).apply {<br>        duration = scaleDownDuration<br>        interpolator = AccelerateDecelerateInterpolator()<br>        start()<br>    }<br><br>    ObjectAnimator.ofPropertyValuesHolder(transitionView, translationYHolder).apply {<br>        duration = translateDuration<br>        interpolator = DecelerateInterpolator()<br>        startDelay = translateDelay<br>        start()<br>    }<br><br>    val disabledColor = resources.getColor(R.color.primary_disabled, theme)<br><br>    // This part was slightly tricky to figure out since button colors behave<br>    // differently in different states - and since we&#39;re using our custom rounded_button<br>    // drawable as the background, we make a copy of it to restore later after the tint animates<br>    val originalBG = transitionView.backgroundTintList<br>    val splashColor = resources.getColor(R.color.primary_color, theme)<br>    ValueAnimator.ofArgb(splashColor, disabledColor).apply {<br>        duration = shiftDuration<br>        interpolator = LinearInterpolator()<br>        addUpdateListener {<br>            transitionView.background.setTint(it.animatedValue as Int)<br>        }<br>        addListener(object : AnimatorListenerAdapter() {<br>            override fun onAnimationEnd(animation: Animator) {<br>                transitionView.isClickable = true<br>                transitionView.background.setTintList(originalBG)<br>            }<br>        })<br>        start()<br>    }<br>    ValueAnimator.ofArgb(getColor(android.R.color.transparent), getColor(android.R.color.white))<br>        .apply {<br>            duration = textFadeDuration<br>            startDelay = textFadeDelay<br>            addUpdateListener {<br>                transitionView.setTextColor(it.animatedValue as Int)<br>            }<br>            start()<br>        }<br>}</pre><blockquote>The code to connect the flow of the two activities is left to the reader — I would suggest something like ActivityResultContract to communicate when and which transitions to use.</blockquote><blockquote>For testing during this tutorial you may use this flow:</blockquote><pre>override fun onCreate() {<br>  ...<br>  startActivity(Intent(this, SplashActivity::class.java))<br>}<br><br>override fun onRestart() {<br>  ...<br>  setupViewsForSplashTransition()<br>  transitionFromSplash()<br>}</pre><p>And that’s it! We’ve connected two of our activities seamlessly — and it should look like this now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*_8aRY15-ceBHY168hR899g.gif" /><figcaption>Splash-to-Login transition</figcaption></figure><h3><strong>Adding a Login-to-Home transition 🔓🔑</strong></h3><p>Wasting no further time, let’s get to adding the main activity. I’m gonna use the bottom navigation activity template from Android Studio and name it MainActivity with, again, the theme set to .PseudoFullScreen</p><p>First, we style our bottom navigation bar to have rounded corners:</p><pre>// MainActivity.kt<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br><br>    binding = ActivityMainBinding.inflate(layoutInflater)<br>    setContentView(binding.root)<br><br>    // Bottom navigation bar with rounded corners<br>    val radius = resources.getDimension(R.dimen.navbar_corner_radius)<br>    val navView: BottomNavigationView = binding.navView<br>    val navBackground = navView.background as MaterialShapeDrawable<br>    navView.background.setTint(getColor(R.color.teal_200))<br>    window.navigationBarColor = getColor(R.color.teal_200)<br>    navBackground.shapeAppearanceModel = navBackground.shapeAppearanceModel<br>        .toBuilder()<br>        .setTopRightCorner(CornerFamily.ROUNDED, radius)<br>        .setTopLeftCorner(CornerFamily.ROUNDED, radius)<br>        .build()<br><br>    // navController needs to be fetched from fragmentmanager otherwise it crashes<br>    // Probably a bug with how the API works - may have been updated since time of writing<br>    val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment_activity_main) as NavHostFragment<br>    val navController = navHostFragment.navController<br>    <br>    navView.setupWithNavController(navController)<br>}</pre><p>Alright, now we just need to “morph” our login button to the bottom navigation bar’s attributes and then fade out LoginActivity</p><p>This animation involves fading out the “Sign in” text (reverse of post-splash transition), shrink the button, translate the button and explode the button into the size of the navigation view — including the border radius — and then finally finishing the activity to reveal MainActivity</p><p>Once again, let’s define some more animation resource values:</p><pre>&lt;!-- integer.xml --&gt;<br>&lt;integer name=&quot;main_login_button_fade_duration&quot;&gt;250&lt;/integer&gt;<br>&lt;integer name=&quot;main_login_button_shrink_duration&quot;&gt;500&lt;/integer&gt;<br>&lt;integer name=&quot;main_login_button_fill_delay&quot;&gt;250&lt;/integer&gt;<br>&lt;integer name=&quot;main_login_button_fill_duration&quot;&gt;500&lt;/integer&gt;<br>&lt;integer name=&quot;main_login_button_translate_duration&quot;&gt;1250&lt;/integer&gt;<br><br>&lt;!-- dimens.xml --&gt;<br>&lt;dimen name=&quot;main_login_shrink_size&quot;&gt;12dp&lt;/dimen&gt;</pre><p>For the sake of example and a sense of dynamism and challenge, let’s make the navbar fragment a different color than the login button:</p><pre>&lt;!-- drawable/bottomnavbar_color.xml --&gt;<br>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;selector xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;&gt;<br>    &lt;item android:state_checked=&quot;true&quot; android:color=&quot;@color/purple_500&quot; /&gt;<br>    &lt;item android:state_checked=&quot;false&quot; android:color=&quot;?android:textColorSecondary&quot;/&gt;<br>&lt;/selector&gt;</pre><pre>&lt;!-- In activity_main.xml --&gt;<br><br>&lt;com.google.android.material.bottomnavigation.BottomNavigationView<br>  ...<br>  app:itemTextColor=&quot;@drawable/bottomnavview_color&quot;<br>  app:itemIconTint=&quot;@drawable/bottomnavview_color&quot;<br>/&gt;</pre><p>At this point we’re practically done with everything but the actual animation — so let’s head back to LoginActivity</p><p>We’re gonna need the size of the system navbar to appropriately size the activity’s navbar fragment (these activities draw behind system bars, remember? — unless ofc you didn’t go the transparent activity route)</p><pre>// LoginActivity.kt<br><br>private var legacyBottomInset = 0<br>private var legacyInsetHeight = 0<br><br>override fun onCreate(savedInstanceState: Bundle?) {<br>  ...<br>  binding.root.setOnApplyWindowInsetsListener { _, insets -&gt;<br>      legacyBottomInset = insets.systemWindowInsetBottom<br>      legacyInsetHeight = insets.systemWindowInsetTop + insets.systemWindowInsetBottom<br>      insets<br>  }<br>}<br><br>// Inset functions should ideally be abstracted out of activities<br>// but those are developmental decisions outside the scope of this guide<br>private fun getWindowBottomInset(): Int {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.R) {<br>        binding.root.rootWindowInsets.getInsetsIgnoringVisibility(<br>            WindowInsetsCompat.Type.systemBars()<br>        ).bottom<br>    }<br><br>    return legacyBottomInset<br>}<br><br>private fun getWindowInsetHeight(): Int {<br>        if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.R) {<br>            binding.root.rootWindowInsets.getInsetsIgnoringVisibility(<br>                WindowInsetsCompat.Type.systemBars()<br>            ).top + getWindowBottomInset()<br>        }<br><br>        return legacyInsetHeight<br>    }</pre><p>Now hang on, there’s a LOT to unpack… HERE WE GO</p><pre>private fun proceedWithTransition() {<br>    binding.login.isClickable = false<br><br>    // Fade the text<br>    // Make the button a circle<br>    // Shrink it while moving it down to the bottom edge of the screen<br>    val transitionView = binding.login<br>    val textFadeDuration = resources.getInteger(R.integer.main_login_button_fade_duration).toLong()<br>    val shrinkSize = resources.getDimensionPixelSize(R.dimen.main_login_shrink_size)<br>    val shrinkDuration = resources.getInteger(R.integer.main_login_button_shrink_duration).toLong()<br>    val fillDuration = resources.getInteger(R.integer.main_login_button_fill_duration).toLong()<br>    val fillDelay = resources.getInteger(R.integer.main_login_button_fill_delay).toLong()<br>    val shiftDuration = resources.getInteger(R.integer.main_login_button_translate_duration).toLong()<br><br>    ValueAnimator.ofArgb(getColor(android.R.color.white), getColor(android.R.color.transparent))<br>        .apply {<br>            duration = textFadeDuration<br>            addUpdateListener {<br>                transitionView.setTextColor(it.animatedValue as Int)<br>            }<br>            start()<br>        }<br><br>    val typedVal = TypedValue()<br>    var actionBarHeight = 0<br>    if (theme.resolveAttribute(android.R.attr.actionBarSize, typedVal, true)) {<br>        actionBarHeight = TypedValue.complexToDimensionPixelSize(<br>            typedVal.data,<br>            resources.displayMetrics<br>        )<br>    }<br><br>    AnimatorSet().apply {<br>        playTogether(<br>            ValueAnimator.ofInt(transitionView.width, shrinkSize).apply {<br>                addUpdateListener {<br>                    transitionView.updateLayoutParams { width = it.animatedValue as Int }<br>                }<br>            },<br>            ValueAnimator.ofInt(transitionView.height, shrinkSize).apply {<br>                addUpdateListener {<br>                    transitionView.updateLayoutParams { height = it.animatedValue as Int }<br>                }<br>            },<br>        )<br>        interpolator = DecelerateInterpolator()<br>        duration = shrinkDuration<br>        startDelay = textFadeDuration<br>        start()<br>    }<br><br>    val bottomInset = getWindowBottomInset()<br>    val deviceWidth = resources.displayMetrics.widthPixels<br>    val finalHeight = bottomInset + actionBarHeight<br><br>    // translation is given as y_final - y_initial &lt;- this changes with the animation, so account for that.<br>    // view.y = 0 starts from under the status bar<br>    // SDK &lt; 30: displayMetrics don&#39;t include system bars, so we add status bar height too<br>    val translationFinal = if (Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.R) {<br>        (resources.displayMetrics.heightPixels - actionBarHeight) -<br>                (transitionView.y - (finalHeight - transitionView.height) / 2) +<br>                (getWindowInsetHeight() - getWindowBottomInset())<br>    } else {<br>        (resources.displayMetrics.heightPixels - actionBarHeight) -<br>                (transitionView.y - (finalHeight - transitionView.height) / 2)<br>    }<br>    ObjectAnimator.ofFloat(transitionView, &quot;translationY&quot;, translationFinal.toFloat()).apply {<br>        interpolator = DecelerateInterpolator()<br>        duration = shiftDuration<br>        startDelay = textFadeDuration<br>        start()<br>    }<br><br>    val startColor = getColor(R.color.primary_color)<br>    val navBarColor = getColor(R.color.purple_200)<br>    val startingCornerRadius = resources.getDimensionPixelSize(R.dimen.login_button_corner).toFloat()<br>    val finalCornerRadius = resources.getDimensionPixelSize(R.dimen.navbar_corner_radius).toFloat()<br>    val transitionViewBg = GradientDrawable().apply {<br>        setColor(startColor)<br>        cornerRadius = startingCornerRadius<br>    }<br>    transitionView.background = transitionViewBg<br>    AnimatorSet().apply {<br>        playTogether(<br>            ValueAnimator.ofInt(transitionView.width, deviceWidth).apply {<br>                addUpdateListener {<br>                    transitionView.updateLayoutParams { width = it.animatedValue as Int }<br>                }<br>            },<br>            ValueAnimator.ofInt(transitionView.height, finalHeight).apply {<br>                addUpdateListener {<br>                    transitionView.updateLayoutParams { height = it.animatedValue as Int }<br>                }<br>            },<br>            ValueAnimator.ofArgb(startColor, navBarColor).apply {<br>                addUpdateListener {<br>                    transitionView.background.setTint(it.animatedValue as Int)<br>                }<br>            },<br>            ValueAnimator.ofFloat(startingCornerRadius, finalCornerRadius).apply {<br>                addUpdateListener {<br>                    val cornerRadius = it.animatedValue as Float<br>                    transitionViewBg.cornerRadii = floatArrayOf(<br>                        cornerRadius,<br>                        cornerRadius,<br>                        cornerRadius,<br>                        cornerRadius,<br>                        finalCornerRadius - cornerRadius,<br>                        finalCornerRadius - cornerRadius,<br>                        finalCornerRadius - cornerRadius,<br>                        finalCornerRadius - cornerRadius<br>                    )<br>                }<br>            }<br>        )<br>        interpolator = DecelerateInterpolator()<br>        duration = fillDuration<br>        startDelay = textFadeDuration + shrinkDuration + fillDelay<br>        addListener(object : AnimatorListenerAdapter() {<br>            override fun onAnimationEnd(animation: Animator) {<br>                startActivity(Intent(this@LoginActivity, MainActivity::class.java))<br>                overridePendingTransition(0, android.R.anim.fade_out)<br>                finish()<br>            }<br>        })<br>        start()<br>    }<br>}</pre><p>Please work please work please work please wor- IT WORKS!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*lp8TQkCgOxH0Lahw6UL-Kw.gif" /><figcaption>Login button to navbar morph transition</figcaption></figure><h3>Parting notes + Demo source code 💻</h3><p>Phew that was a journey eh? Congratulations if you made it this far! 🎉</p><p>You may have noticed that the code here can be drastically improved in many ways — and I think it’s because transitions are so UI-specific that providing a tutorial that conveys an idea but also is somewhat adaptable is very hard, to say the least 😅</p><p>Try coming up with ways to improve the provided code or transitions, maybe make the non-animating views fade out and away like shown in the hubSFU preview. Try experimenting with gestures, inputs, maybe even custom paths and timing curves. It can be time-consuming but that’s also something that makes the process extremely rewarding. Feel free to leave feedback or suggestions! 😄</p><p>The demo source code is available here: <a href="https://github.com/tanish2k09/Advanced-android-activity-transition"><em>https://github.com/tanish2k09/Advanced-android-activity-transition</em></a></p><p>Find out more about me here: <a href="https://manku.dev/"><em>manku.dev</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ec5a76c27e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>