<?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 Piotr Prus on Medium]]></title>
        <description><![CDATA[Stories by Piotr Prus on Medium]]></description>
        <link>https://medium.com/@piotrprus?source=rss-27f05ec13608------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*idZ19RPwag4SivbmyTvt1Q.jpeg</url>
            <title>Stories by Piotr Prus on Medium</title>
            <link>https://medium.com/@piotrprus?source=rss-27f05ec13608------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:59:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@piotrprus/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[Motion Blur for a Spinning Wheel in Jetpack Compose]]></title>
            <link>https://proandroiddev.com/motion-blur-for-a-spinning-wheel-in-jetpack-compose-368c1647224d?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/368c1647224d</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[motion-design]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Wed, 04 Mar 2026 20:04:06 GMT</pubDate>
            <atom:updated>2026-03-04T20:04:06.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YAB7uxxoUstWDC-3" /><figcaption>Photo by <a href="https://unsplash.com/@introspectivedsgn?utm_source=medium&amp;utm_medium=referral">Erik Mclean</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The wheel that felt wrong</h3><p>We were building a referral reward feature — a Fortune Wheel that spins and lands on a prize segment. The animation logic worked. The physics felt right. Deceleration, overshoot, settle. But <br> watching it spin at full speed, something was off. It looked like a screenshot rotating, not a wheel. Every segment was razor-sharp, perfectly readable, even at 450 degrees per second. Real<br> spinning objects don’t look like that.</p><p>The wheel needed motion blur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*iXi0VBuFwfvF7A2onxzkOg.gif" /></figure><h3>Drawing the Wheel: The Foundation</h3><p>Before we talk about blur, the wheel’s draw structure matters enormously — the blur solution depends on it.</p><p>The wheel is a Canvas composable. Each segment is an arc filled with a radial gradient, outlined with a stroke, bordered by glowing radial lines, and labelled with price text rotated to face<br> outward. All of this lives in a single DrawScope extension function.</p><pre>  private fun DrawScope.drawWheelSegment(<br>      segment: RandomReferralRewardSegment,<br>      startAngle: Float,<br>      sweepAngle: Float,<br>      radius: Float,<br>      textMeasurer: TextMeasurer,<br>      segmentInnerColor: Color,<br>      segmentOuterColor: Color,<br>  ) {<br>      val center = Offset(size.width / 2f, size.height / 2f)<br><br>      // Glow on radial dividers — Screen blend + blur mask<br>      drawIntoCanvas { canvas -&gt;<br>        drawArc(brush = fillBrush, startAngle = startAngle,<br>          sweepAngle = sweepAngle, useCenter = true,<br>          topLeft = Offset(center.x - radius, center.y - radius),<br>          size = Size(radius * 2f, radius * 2f))<br><br>        // Outline stroke<br>        drawArc(color = ColorTokens.neutral1.a76, startAngle = startAngle,<br>          sweepAngle = sweepAngle, useCenter = true,<br>          topLeft = Offset(center.x - radius, center.y - radius),<br>          size = Size(radius * 2f, radius * 2f),<br>          style = Stroke(width = outlineWidth))<br><br>        // Price text, rotated to face outward<br>        val textLayoutResult = textMeasurer.measure(priceText, textStyle)<br>        val middleAngle = startAngle + sweepAngle / 2f<br>        val angleInRadians = (middleAngle * PI / 180f).toFloat()<br>        val textX = center.x + radius * 0.8f * cos(angleInRadians) - textLayoutResult.size.width / 2f<br>        val textY = center.y + radius * 0.8f * sin(angleInRadians) - textLayoutResult.size.height / 2f<br><br>        rotate(degrees = middleAngle + 90f,<br>             pivot = Offset(textX + textLayoutResult.size.width / 2f,<br>                            textY + textLayoutResult.size.height / 2f)) {<br>          drawText(textLayoutResult, topLeft = Offset(textX, textY))<br>      }<br>  }</pre><p>All segments and indicator dots are then gathered into a single lambda:</p><pre>  val drawWheelContent: DrawScope.() -&gt; Unit = {<br>      segments.forEach { segment -&gt;<br>          drawWheelSegment(segment, startAngle, sweepAngle, radius, ...)<br>      }<br>      segments.forEachIndexed { index, _ -&gt;<br>          drawIndicatorDot(startAngle = startAngleOffset + index * sweepAngle, ...)<br>      }<br>  }</pre><p>This is the most important structural decision in the whole implementation. drawWheelContent is a typed function reference — DrawScope.() -&gt; Unit — so it can be passed to any number of Canvas<br> composables. The drawing logic is defined once; the canvas can be instantiated as many times as needed. Everything that follows depends on this.</p><h3>Measuring Velocity</h3><p>Motion blur intensity should reflect how fast the wheel is actually moving. We measure real velocity from the Animatable that drives the rotation, using snapshotFlow to observe frame-by-frame<br> value changes:</p><pre>  var motionBlurVelocity by remember { mutableFloatStateOf(0f) }<br><br>  LaunchedEffect(rotateAnimatable) {<br>      var prevValue = rotateAnimatable.value<br>      var prevTimeMs = System.currentTimeMillis()<br>      snapshotFlow { rotateAnimatable.value }.collect { value -&gt;<br>          val nowMs = System.currentTimeMillis()<br>          val dt = nowMs - prevTimeMs<br>          if (dt &gt; 0) {<br>              motionBlurVelocity = (value - prevValue) / dt * 1000f // deg/s<br>          }<br>          prevValue = value<br>          prevTimeMs = nowMs<br>      }<br>  }</pre><p>From velocity we derive a blurMultiplier in [0, 1]. Phase 1 spins at a constant 450 deg/s. Blur fades in from half that speed so it doesn’t snap on suddenly:</p><pre>val phase1VelocityDegPerSec = 360f / LINEAR_ROTATION_DURATION * 1000f // 450 deg/s<br>  val motionBlurThreshold = phase1VelocityDegPerSec / 2f                 // 225 deg/s<br><br>  val blurMultiplier = ((abs(motionBlurVelocity) - motionBlurThreshold) / motionBlurThreshold)<br>      .coerceIn(0f, 1f)<br><br>  val spinDirection = if (motionBlurVelocity &gt;= 0f) 1f else -1f</pre><p>Both blur implementations below are driven by the same two values: blurMultiplier and spinDirection.</p><h3>The Shader Solution (API 33+)</h3><p>The physically correct way to blur a rotating object is a rotational accumulation blur — sample the image at multiple positions rotated behind the current frame and blend them together. On<br> Android 13 (API 33) and above, this is possible with AGSL (RuntimeShader) applied as a RenderEffect directly on the composable layer.</p><h4><strong>Writing the AGSL Shader</strong></h4><p>AGSL (Android Graphics Shading Language) is Google’s shading language for Android, closely related to GLSL. A RuntimeShader receives the composable’s rendered layer as a uniform shader and can<br> sample it at arbitrary coordinates using .eval().</p><p>The shader takes 16 samples, each rotated slightly further in the trailing direction. Weights fall off linearly from 1.0 at the current frame to 0.15 at the farthest trailing sample:</p><pre>  private const val ROTATIONAL_BLUR_AGSL = &quot;&quot;&quot;<br>  uniform shader image;<br>  uniform float blurAngle;<br>  uniform float centerX;<br>  uniform float centerY;<br>  uniform float spinDir;<br><br>  half4 main(float2 coord) {<br>      const int SAMPLES = 16;<br>      half4 color = half4(0.0, 0.0, 0.0, 0.0);<br>      float totalWeight = 0.0;<br>      for (int i = 0; i &lt; SAMPLES; i++) {<br>          float t     = float(i) / float(SAMPLES - 1);<br>          float angle = -t * blurAngle * spinDir;<br>          float2 delta   = coord - float2(centerX, centerY);<br>          float cosA     = cos(angle);<br>          float sinA     = sin(angle);<br>          float2 rotated = float2(<br>              delta.x * cosA - delta.y * sinA,<br>              delta.x * sinA + delta.y * cosA<br>          ) + float2(centerX, centerY);<br>          float weight = 1.0 - t * 0.85;<br>          color       += image.eval(rotated) * weight;<br>          totalWeight += weight;<br>      }<br>      return totalWeight &gt; 0.0 ? color / totalWeight : half4(0.0, 0.0, 0.0, 0.0);<br>  }<br>  &quot;&quot;&quot;</pre><p>blurAngle is the total angular spread in radians. spinDir (+1 or −1) ensures the smear always trails behind the direction of rotation. The image.eval(rotated) call samples the rendered wheel<br> bitmap at a rotated coordinate — this is what makes the blur rotational rather than linear.</p><h4><strong>Applying the Shader</strong></h4><p>The helper function compiles the shader program and binds it to the layer:</p><pre>  @RequiresApi(Build.VERSION_CODES.TIRAMISU)<br>  private fun rotationalBlurEffect(<br>      blurAngleRad: Float,<br>      spinDirection: Float,<br>      centerX: Float,<br>      centerY: Float,<br>  ): RenderEffect {<br>      val shader = RuntimeShader(ROTATIONAL_BLUR_AGSL)<br>      shader.setFloatUniform(&quot;blurAngle&quot;, blurAngleRad)<br>      shader.setFloatUniform(&quot;centerX&quot;, centerX)<br>      shader.setFloatUniform(&quot;centerY&quot;, centerY)<br>      shader.setFloatUniform(&quot;spinDir&quot;, spinDirection)<br>      return RenderEffect.createRuntimeShaderEffect(shader, &quot;image&quot;)<br>  }</pre><p>The “image” string is the name of the uniform shader in the AGSL source — it tells the system which uniform receives the layer’s rendered output.</p><p>This is applied in the graphicsLayer of the main wheel canvas. Note that graphicsLayer { renderEffect } expects androidx.compose.ui.graphics.RenderEffect, not the platform<br> android.graphics.RenderEffect — the .asComposeRenderEffect() extension handles the conversion:</p><pre>  Canvas(<br>      modifier = Modifier<br>          .matchParentSize()<br>          .graphicsLayer {<br>              compositingStrategy = CompositingStrategy.Offscreen<br>              rotationZ = visualRotation<br>              if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>                  // Max angular spread at full speed: 8 degrees (~0.14 rad).<br>                  renderEffect = if (blurMultiplier &gt; 0f) {<br>                      rotationalBlurEffect(<br>                          blurAngleRad = Math.toRadians(blurMultiplier * 8.0).toFloat(),<br>                          spinDirection = spinDirection,<br>                          centerX = size.width / 2f,<br>                          centerY = size.height / 2f,<br>                      ).asComposeRenderEffect()<br>                  } else null<br>              }<br>          }<br>          .padding(16.dp),<br>      onDraw = drawWheelContent<br>  )</pre><p>The rotationZ rotates the wheel to the current frame’s position. The renderEffect is applied to the layer’s content in local space before the rotation transform is composited by the renderer.<br> This means the blur smear is computed on the wheel pixels, and the whole blurred result is then placed at the correct rotation angle — which is exactly the right order of operations.</p><h4><strong>The API Level Constraint</strong></h4><p>RuntimeShader was introduced in API 33 (Android 13, codename Tiramisu). It is not available in API 31 or 32, even though RenderEffect itself arrived in API 31. The built-in RenderEffect factory<br> methods from API 31 (createBlurEffect, createColorFilterEffect, etc.) do not include rotational or directional blur — only Gaussian blur. A custom AGSL shader is the only way to get rotational<br> blur, and that requires API 33.</p><h3>The Ghost Layer Fallback (API 32 and Below)</h3><p>For devices below API 33, we approximate the same visual result using a technique that works on every Android version: render the wheel multiple times at slightly different rotation angles, each<br> with decreasing opacity. When layered on top of each other, the result reads as a trailing smear.</p><p>This is where drawWheelContent being a reusable lambda pays off — we pass the same lambda to multiple Canvas composables. The drawing cost is real (each canvas traversal re-executes all the<br> segment fills, gradients, text, and glow lines), but three additional layers during a 1.5-second spin is imperceptible on any device that can run Compose at all.</p><pre>  if (blurMultiplier &gt; 0f &amp;&amp; Build.VERSION.SDK_INT &lt; Build.VERSION_CODES.TIRAMISU) {<br>      // Closest trail: 2° behind, 80% max opacity<br>      Canvas(<br>          modifier = Modifier.matchParentSize().graphicsLayer {<br>              compositingStrategy = CompositingStrategy.Offscreen<br>              rotationZ = visualRotation - 2f * spinDirection<br>              alpha = 0.8f * blurMultiplier<br>          }.padding(16.dp),<br>          onDraw = drawWheelContent<br>      )<br>      // 4° behind, 60% max opacity<br>      Canvas(<br>          modifier = Modifier.matchParentSize().graphicsLayer {<br>              compositingStrategy = CompositingStrategy.Offscreen<br>              rotationZ = visualRotation - 4f * spinDirection<br>              alpha = 0.6f * blurMultiplier<br>          }.padding(16.dp),<br>          onDraw = drawWheelContent<br>      )<br>      // 6° behind, 40% max opacity<br>      Canvas(<br>          modifier = Modifier.matchParentSize().graphicsLayer {<br>              compositingStrategy = CompositingStrategy.Offscreen<br>              rotationZ = visualRotation - 6f * spinDirection<br>              alpha = 0.4f * blurMultiplier<br>          }.padding(16.dp),<br>          onDraw = drawWheelContent<br>      )<br>      // 8° behind, 30% max opacity (farthest trail)<br>      Canvas(<br>          modifier = Modifier.matchParentSize().graphicsLayer {<br>              compositingStrategy = CompositingStrategy.Offscreen<br>              rotationZ = visualRotation - 8f * spinDirection<br>              alpha = 0.3f * blurMultiplier<br>          }.padding(16.dp),<br>          onDraw = drawWheelContent<br>      )<br>  }</pre><p>CompositingStrategy.Offscreen forces each layer into its own intermediate bitmap before blending. This ensures BlendMode operations inside the wheel drawing (the Screen blend on the glow lines)<br> work correctly, and that alpha is applied to the whole composited layer rather than per-pixel independently.</p><p>The ghost layers are fully absent from the composition tree when blurMultiplier == 0 — the if guard means Compose never lays them out or draws them at rest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*YVEWWONjCIFFitvkuFZODQ.gif" /></figure><h4>Performance: Canvas in Compose</h4><p>A Canvas composable does not trigger Compose recomposition on every frame. Once placed, its onDraw lambda executes on the render thread directly via DrawScope — the Compose wrappers are thin<br> adapters over native android.graphics primitives. The wheel itself redraws every frame only because its graphicsLayer rotationZ changes; this is a layer matrix update, handled by the render<br> thread without touching the Compose node tree.</p><p>For the shader path, RuntimeShader compilation happens once per rotationalBlurEffect() call. AGSL programs are not cached by the system between calls, which means a new<br> RuntimeShader(AGSL_SOURCE) on each recomposition would compile on every frame during spinning — a non-trivial cost. If profiling reveals a problem, the fix is to remember the RuntimeShader<br> instance and update its uniforms in-place, then remember the RenderEffect wrapping it.</p><p>For the ghost layer path, each additional canvas re-executes drawWheelContent fully. Four ghost layers means four times the draw work during spinning. In practice, on mid-range devices, this<br> adds no perceptible jank across a 1.5-second spin phase, but it is real GPU work. A stricter optimisation would be to reduce ghost layers at lower frame rates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/230/1*iXi0VBuFwfvF7A2onxzkOg.gif" /></figure><h3>Putting It Together</h3><p>The blurMultiplier is the single control surface for both implementations. Zero means no blur anywhere. One means the shader is at full angular spread (or all ghost layers at full opacity). The<br> transition between those states is driven by real measured velocity, so the blur naturally fades out during deceleration without any additional code — the wheel slows down, blurMultiplier drops,<br> and the blur dissolves.</p><p>The end result: a wheel that feels physically plausible on every supported Android version. Shader-quality rotational blur on API 33 and above, a convincing approximation on everything below — <br> same velocity measurement, same blurMultiplier control, different render paths.</p><p><strong><em>Thanks for reading. Happy composing.</em></strong></p><p><em>Special thanks to </em><a href="https://medium.com/u/3f9b9c30bec7"><em>Rebecca Franks</em></a><em> for sparking the ghost-layer idea, and to </em><a href="https://medium.com/u/c967b7e51f8b"><em>Romain Guy</em></a><em> for pointing the way to RuntimeShader and explaining how<br> path-based sampling turns a blur into true rotational motion.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=368c1647224d" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/motion-blur-for-a-spinning-wheel-in-jetpack-compose-368c1647224d">Motion Blur for a Spinning Wheel in Jetpack Compose</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[Dynamic Height Top App Bar in Jetpack Compose]]></title>
            <link>https://proandroiddev.com/dynamic-height-top-app-bar-in-jetpack-compose-69d95b9dc4b6?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/69d95b9dc4b6</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[androiddev]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Wed, 28 Jan 2026 14:41:13 GMT</pubDate>
            <atom:updated>2026-01-28T14:41:13.713Z</atom:updated>
            <content:encoded><![CDATA[<h4>Master dynamic height Top App Bars in Jetpack Compose. Build flexible, reactive headers that go beyond the limitations of standard Material 3 components.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kXT-8cj_vGcB_RVB" /><figcaption>Photo by <a href="https://unsplash.com/@steve_j?utm_source=medium&amp;utm_medium=referral">Steve Johnson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever wanted to create a detailed header that gracefully collapses into a simple title bar?</p><p>We often encounter designs where a top app bar needs to react fluidly to the content scrolling beneath it. While Material Design 3 provides great defaults, sometimes we need more control.</p><p>In this article, we’ll build a <strong>Dynamic Height Top App Bar</strong> in Jetpack Compose that gives you complete freedom over how your app bar transforms during scroll.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*CQjYVKOUf-XK8I2Rlg__sw.gif" /></figure><h4>The Problem with Standard App Bars</h4><p>Material3’s <em>TopAppBar</em>, <em>MediumTopAppBar</em>, and <em>LargeTopAppBar</em> are fantastic for standard use cases. They handle the “big to small” text transition beautifully.</p><p>However, they have limitations:<br> — Restricted Layouts: You are mostly limited to a <em>title</em>, <em>navigationIcon</em>, and <em>actions</em>.<br> — Predefined Transformations: You can’t easily animate arbitrary elements (like an avatar resizing or buttons fading out) based on the scroll position.<br> — Two-Slot System: Material’s <em>TwoRowsTopAppBar</em> (used for Medium and Large) essentially switches between a “collapsed” and “expanded” title slot. It doesn’t give you a continuous scroll progress value to drive custom animations.</p><p>If you look at the source code for <em>TwoRowsTopAppBar</em> in <em>AppBar.kt</em>, you’ll see it calculates a <em>collapsedFraction</em> but mostly keeps its internal logic private or internal, making it hard to extend for custom behaviors.</p><h4>Our Solution: A Content-Aware Dynamic Bar</h4><p>We want a Top App Bar that:</p><ol><li>Accepts a <em>minHeight</em> and <em>maxHeight</em>.</li><li>Connects to a <em>TopAppBarScrollBehavior</em> to react to scroll events.</li><li>Crucially, exposes the current <em>offset</em> or <em>progress</em> to its content, allowing us to animate anything we want.</li></ol><p>Let’s build <strong>DynamicHeightTopAppBar</strong>.</p><h4>Step 1: Defining the API</h4><p>We’ll start by defining our Composable. It needs to know the height limits and the scroll behavior. The <em>content</em> lambda will receive the current <em>offsetDp</em> (how much we’ve scrolled) and <em>statusBarHeight</em> (so we can draw behind the status bar if needed).</p><pre>@OptIn(ExperimentalMaterial3Api::class)<br>@Composable<br>fun DynamicHeightTopAppBar(<br>    modifier: Modifier = Modifier,<br>    minHeight: Dp,<br>    maxHeight: Dp,<br>    scrollBehavior: TopAppBarScrollBehavior?,<br>    content: @Composable (offsetDp: Dp, statusBarHeight: Dp) -&gt; Unit<br>) {<br>    // ... implementation<br>}</pre><h4>Step 2: Handling Height and Scroll Logic</h4><p>We can reuse some logic from Material’s implementation. Specifically, <em>TopAppBarScrollBehavior</em> maintains a <em>TopAppBarState</em> which tracks the <em>heightOffset</em>.</p><p>We need to tell the state how much it <strong>can</strong> scroll. The <em>heightOffsetLimit </em>should be the difference between our min and max height.</p><pre>    val density = LocalDensity.current<br>    val maxHeightPx: Float<br>    val minHeightPx: Float<br>    <br>    with(density) {<br>        maxHeightPx = maxHeight.toPx()<br>        minHeightPx = minHeight.toPx()<br>    }<br><br>    // Set the app bar&#39;s height offset limit to collapse from maxHeight to minHeight<br>    SideEffect {<br>        if (scrollBehavior?.state?.heightOffsetLimit != minHeightPx - maxHeightPx) {<br>            scrollBehavior?.state?.heightOffsetLimit = minHeightPx - maxHeightPx<br>        }<br>    }</pre><h4>Step 3: Reusing Material’s Fling Logic</h4><p>One of the trickiest parts of a custom app bar is handling the “fling” or “snap” behavior. If a user drags the bar halfway and lets go, it should either snap open or closed, or continue its momentum.</p><p>The Material library has a <em>settleAppBar</em> function that handles this perfectly. Since it’s often <em>private</em> or <em>internal</em> in the library, we’ve brought a copy of it into our file to ensure our custom bar feels just like a native one.</p><blockquote>Note: The <em>settleAppBar</em> function uses <em>DecayAnimationSpec</em> and <em>AnimationState</em> to calculate where the bar should land based on velocity.</blockquote><p>We attach this logic using a <em>draggable</em> modifier:</p><pre>    // Set up support for resizing the top app bar when vertically dragging the bar itself<br>    val appBarDragModifier =<br>        if (scrollBehavior != null &amp;&amp; !scrollBehavior.isPinned) {<br>            Modifier.draggable(<br>                orientation = Orientation.Vertical,<br>                state = rememberDraggableState { delta -&gt; <br>                    scrollBehavior.state.heightOffset += delta <br>                },<br>                onDragStopped = { velocity -&gt;<br>                    settleAppBar(<br>                        scrollBehavior.state,<br>                        velocity,<br>                        scrollBehavior.flingAnimationSpec,<br>                        scrollBehavior.snapAnimationSpec<br>                    )<br>                }<br>            )<br>        } else {<br>            Modifier<br>        }</pre><h4>Step 4: The Content Layout</h4><p>Now for the fun part. We calculate the <em>currentHeight</em> and the <em>offsetDp</em> to pass to our content.</p><p>We also handle <em>WindowInsets</em> to ensure we can draw edge-to-edge (behind the status bar) while giving the content the information it needs to avoid overlapping system icons.</p><pre>    // Calculate current offset in Dp to pass to content<br>    val currentHeightOffset = scrollBehavior?.state?.heightOffset ?: 0f<br>    val offsetDp = with(density) { currentHeightOffset.absoluteValue.toDp() }<br>    <br>    // Get status bar height<br>    val statusBarHeight = with(density) { <br>        WindowInsets.statusBars.getTop(density).toDp()<br>    }<br>    <br>    // Calculate total height<br>    val currentHeight = maxHeight + statusBarHeight + with(density) { currentHeightOffset.toDp() }<br><br>    Surface(modifier = modifier.then(appBarDragModifier), color = Color.Transparent) {<br>        Box(<br>            modifier = Modifier<br>                .clipToBounds()<br>                .height(currentHeight)<br>        ) {<br>            content(offsetDp, statusBarHeight)<br>        }<br>    }</pre><h3>Usage Example: The Shrinking Profile Header</h3><p>Now let’s use our <em>DynamicHeightTopAppBar</em> to build a complex profile header.</p><p>We want:<br> — An avatar that shrinks from 50dp to 20dp.<br> — A username that scales from 24sp to 14sp.<br> — Action buttons that fade out as we collapse.</p><p>Here is how we implement it :</p><pre>@Composable<br>fun MyTopAppBar(modifier: Modifier = Modifier, scrollBehavior: TopAppBarScrollBehavior) {<br>    DynamicHeightTopAppBar(<br>        scrollBehavior = scrollBehavior,<br>        modifier = modifier.fillMaxWidth(),<br>        minHeight = 56.dp,<br>        maxHeight = 160.dp<br>    ) { offsetDp, statusBarHeight -&gt;<br>        <br>        // 1. Calculate Progress (0.0 -&gt; Collapsed, 1.0 -&gt; Expanded)<br>        val maxOffset = 104.dp // (maxHeight - minHeight)<br>        val progress = 1f - (offsetDp.value / maxOffset.value).coerceIn(0f, 1f)<br><br>        Box(<br>            modifier = Modifier<br>                .fillMaxSize()<br>                .background(MaterialTheme.colorScheme.primaryContainer)<br>        ) {<br>            Row(<br>                modifier = Modifier<br>                    .fillMaxSize()<br>                    .padding(top = statusBarHeight) // Respect status bar<br>                    .padding(horizontal = 16.dp),<br>                verticalAlignment = Alignment.CenterVertically,<br>                horizontalArrangement = Arrangement.spacedBy(12.dp)<br>            ) {<br>                // 2. Dynamic Avatar Size<br>                val avatarSize = (20.dp.value + (50.dp.value - 20.dp.value) * progress).dp<br><br>                UserAvatar(<br>                    borderSize = (1f + progress).dp,<br>                    backgroundColor = Color.LightGray,<br>                    avatarSize = avatarSize<br>                )<br><br>                // 3. Dynamic Font Size<br>                val fontSize = (14f + (24f - 14f) * progress).sp<br><br>                Text(<br>                    text = &quot;John Doe&quot;,<br>                    fontSize = fontSize,<br>                    modifier = Modifier.weight(1f)<br>                )<br><br>                // 4. Fade out actions<br>                // Fade out quickly: 0dp to 30dp scroll<br>                val actionAlpha = (1f - (offsetDp.value / 30f)).coerceIn(0f, 1f)<br><br>                Row(<br>                    modifier = Modifier.alpha(actionAlpha),<br>                    horizontalArrangement = Arrangement.spacedBy(8.dp)<br>                ) {<br>                    // Action Icons...<br>                }<br>            }<br>        }<br>    }<br>}</pre><h4>Key Differences from Material</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IuTt9Nqc-B4m5EzIQjLsYg.png" /></figure><h3>Conclusion</h3><p>By stripping away the slot-based restrictions of the standard Material Top App Bar and exposing the raw scroll offset, we unlock a world of creative possibilities. We can reuse the robust scroll physics (via <em>TopAppBarScrollBehavior</em> and <em>settleAppBar</em>) while maintaining complete control over the visual presentation.</p><p>This approach is perfect for profile screens, detailed product headers, or any screen where you want to provide a rich, immersive experience that gets out of the way as the user consumes content.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69d95b9dc4b6" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/dynamic-height-top-app-bar-in-jetpack-compose-69d95b9dc4b6">Dynamic Height Top App Bar in Jetpack Compose</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[Android UI: Staggered enter animation]]></title>
            <link>https://medium.com/tilt-engineering/android-ui-staggered-enter-animation-445da4998031?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/445da4998031</guid>
            <category><![CDATA[motion-design]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Tue, 13 Jan 2026 23:14:44 GMT</pubDate>
            <atom:updated>2026-01-13T23:14:44.339Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3yKcVCXTqWNi92Ix" /><figcaption>Photo by <a href="https://unsplash.com/@arttoinspire?utm_source=medium&amp;utm_medium=referral">Xiangkun ZHU</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The use-case</h3><p>When it comes to animated visibility in Jetpack Compose, there are a number of built-in options to choose from. However, orchestrating these into a cohesive reveal chain animation is often not straightforward and can lead to code that is difficult to read. Faced with design prototypes requiring a polished “staggered” entrance for UI elements, the goal was to create a reusable solution that could be applied to any UI component, regardless of its specific state. In this post, we will explore existing visibility animation options and present a custom Modifier-based solution that simplifies the entire process.</p><p>When a screen loads with multiple elements, a standard “instant” appearance can feel jarring. To achieve a more premium feel, we often want elements to animate one by one in a chained reveal/fade effect.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FBCiIRkrIUrYGtvfs0u%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FBCiIRkrIUrYGtvfs0u&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExczBudWt1YmEwYXlneWJ3dTlsOWtxYnFvbnpmOHp5N2xhczdwdWFsYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FBCiIRkrIUrYGtvfs0u%2Fgiphy.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc6478ff91a4c4bd67e0a4295b3e8e12/href">https://medium.com/media/cc6478ff91a4c4bd67e0a4295b3e8e12/href</a></iframe><h3>Exploring AnimatedVisiblity</h3><p>Jetpack Compose provides the AnimatedVisibility composable, which is an excellent wrapper for basic enter/exit transitions:</p><pre>var visible by remember { mutableStateOf(true) }<br>val density = LocalDensity.current<br><br>AnimatedVisibility(<br>    visible = visible,<br>    enter = fadeIn(),<br>    exit = fadeOut()<br>) {<br>    Text(<br>        &quot;Hello&quot;,<br>        Modifier<br>            .fillMaxWidth()<br>            .height(200.dp)<br>    )<br>}</pre><p>AnimatedVisibility is a great wrapper over the UI components that can be used for staggered animation by adding the delay to any of the animation specs:</p><pre>fun fadeIn(<br>    animationSpec: FiniteAnimationSpec&lt;Float&gt; = spring(stiffness = Spring.StiffnessMediumLow),<br>    initialAlpha: Float = 0.0f<br>): EnterTransition<br><br>&lt;T : Any?&gt; TweenSpec(<br>    durationMillis: Int = DefaultDurationMillis,<br>    delay: Int = 0,<br>    easing: Easing = FastOutSlowInEasing<br>)</pre><p>This can technically serve our purpose for staggered animations by adding a delay to the animation specs. However, this approach introduces significant overhead:</p><ul><li><strong>State Management:</strong> Every single component requires a Boolean state to trigger the animation.</li><li><strong>Boilerplate:</strong> Manually coordinating these booleans to flip after specific delays makes the code complex and prone to errors.</li><li><strong>Redundancy:</strong> Since these elements are often ready to render immediately upon screen load, managing their “visibility” as a separate state feels like unnecessary effort.</li></ul><h3>Value-based animation</h3><blockquote>The animate*AsState functions are the simplest animation APIs in Compose for animating a single value. You only provide the target value (or end value), and the API starts animation from the current value to the specified value.</blockquote><p>The animate as state is interesting alternative that could be used for our use case, lets see the basic implementation.</p><pre>@Composable<br>fun animateFloatAsState(<br>    targetValue: Float,<br>    animationSpec: AnimationSpec&lt;Float&gt; = defaultAnimation,<br>    visibilityThreshold: Float = 0.01f,<br>    label: String = &quot;FloatAnimation&quot;,<br>    finishedListener: ((Float) -&gt; Unit)? = null<br>): State&lt;Float&gt;</pre><p>While animateFloatAsState is a powerful alternative, it shares the same drawback as AnimatedVisibility: it requires extra fields in the ViewModel or Composable to hold the animated value and manage the trigger logic for every component.</p><h3>The Custom Modifier Solution</h3><p>Since most “enter” animations don’t actually depend on a change in business logic — they simply need to fire when the element is first rendered — we can leverage the onPlaced modifier.</p><p>The onPlaced modifier is called after a layout has been positioned but before it is rendered to the view. This provides the perfect hook to trigger a &quot;one-and-done&quot; entrance animation without needing to manage external Boolean states.</p><h3>Breaking down the enterAnimation modifier</h3><p>By creating a custom extension function on Modifier, we can enable smooth animations for any Composable. Let’s dissect how this solution works.</p><h4>1. Defining Animation Parameters</h4><p>The function accepts parameters that control the behavior of the motion, allowing for flexibility across different UI designs:</p><ul><li><strong>Direction:</strong> Where the component slides from.</li><li><strong>Duration/Easing:</strong> The timing and “feel” of the movement and opacity.</li><li><strong>Delay:</strong> The key to creating the staggered “chain” effect.</li></ul><h4>2. Setting up Composable State</h4><p>Inside the modifier, we use remember to track internal animation values:</p><ul><li>Animatable objects for movement and alpha.</li><li>A dimension state to calculate pixel offsets based on the device&#39;s density.</li></ul><h4>3. Handling Component Placement</h4><p>The onPlaced logic triggers the animation sequence:</p><pre>.onPlaced {<br>    dimension = with(density) { offsetDp.roundToPx() }<br>    if (anim.value == 1f) { // Prevents re-triggering on recomposition<br>        scope.launch {<br>            delay(placementDelayMillis)<br>            anim.animateTo(<br>                targetValue = 0f,<br>                animationSpec = tween(durationMillis, easing = easing)<br>            )<br>            onAnimationFinished()<br>        }<br>        // Concurrent Alpha Animation<br>        scope.launch {<br>            delay(placementDelayMillis)<br>            alphaAnim.animateTo(1f, tween(durationMillisAlpha, easing = alphaEasing))<br>        }<br>    }<br>}</pre><h4>4. Applying the Effects</h4><p>Finally, the logic applies the offset and graphicsLayer transformations. The offset modifier handles the physical movement based on the chosen direction, while graphicsLayer manages scaling and opacity.</p><h3>How to Use It</h3><p>The beauty of this approach is its simplicity. To animate a piece of text with a 100ms delay, you simply append the modifier:</p><pre>Text(<br>    &quot;Animated Text&quot;,<br>    modifier = Modifier.enterAnimation(<br>        animationDirection = AnimationDirection.UP,<br>        durationMillis = 300,<br>        placementDelayMillis = 100L<br>    )<br>)</pre><p>Buttons staggered animation:</p><pre>buttons.forEachIndexed { index, _ -&gt;<br>    RoomActionButton(<br>        // ... other parameters<br>        modifier = Modifier<br>            .enterAnimation(<br>                animationDirection = AnimationDirection.UP,<br>                offsetDp = 12.dp,<br>                durationMillis = 300,<br>                placementDelayMillis = index * 20L<br>            )<br>    )<br>}</pre><h3>Conclusion</h3><p>By moving animation logic into a custom Modifier, we eliminate the need for cumbersome state management in our screens. This enterAnimation tool provides a clean, reusable way to create professional, staggered UI transitions that are easy to read and maintain.</p><h3>TL;DR</h3><p>Here is the complete code for the reusable modifier:</p><pre>package retrolabs.retroapp.android.uikit.motion<br><br>import androidx.compose.animation.core.Animatable<br>import androidx.compose.animation.core.EaseOutBack<br>import androidx.compose.animation.core.Easing<br>import androidx.compose.animation.core.LinearEasing<br>import androidx.compose.animation.core.tween<br>import androidx.compose.foundation.layout.offset<br>import androidx.compose.runtime.getValue<br>import androidx.compose.runtime.mutableIntStateOf<br>import androidx.compose.runtime.mutableStateOf<br>import androidx.compose.runtime.remember<br>import androidx.compose.runtime.rememberCoroutineScope<br>import androidx.compose.runtime.setValue<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.composed<br>import androidx.compose.ui.graphics.graphicsLayer<br>import androidx.compose.ui.layout.onPlaced<br>import androidx.compose.ui.platform.LocalDensity<br>import androidx.compose.ui.unit.Dp<br>import androidx.compose.ui.unit.IntOffset<br>import androidx.compose.ui.unit.dp<br>import kotlinx.coroutines.delay<br>import kotlinx.coroutines.launch<br><br>/**<br> * Add an [Modifier] configured with the given duration, direction, delay and easing curve.<br> * This modifier adds the placement animation to the component. It animates just one time for<br> * composition. This should be used for components that do not have state or the visibility<br> * of this components is not controlled by the state. For example: Use it to make enterAnimation<br> * of static element like button, image, etc.<br> *<br> * For state-base animations use helper object: [RetroTransition]<br> *<br> * @param animationDirection direction towards targetValue of animation<br> * @param durationMillis the amount of time in milliseconds that animation of positioning takes<br> * @param durationMillisAlpha the amount of time in milliseconds that animation of opacity takes<br> * @param easing the easing curve that will be used for positioning animation (move)<br> * @param alphaEasing the easing curve that will be used for opacity animation<br> * If you want to apply negative walue, consider changing the [animationDirection]<br> * @param offsetDp value of offset in density pixels.<br> * @param placementDelayMillis the amount of time in milliseconds that animation waits before it starts.<br> * It can be used to create beautiful staggering effect<br> * @param onAnimationFinished is a lambda that is called when placement animation is finished. It takes the delay into account.<br> */<br>fun Modifier.enterAnimation(<br>    animationDirection: AnimationDirection = AnimationDirection.DOWN,<br>    durationMillis: Int = RetroAnimDuration.T3,<br>    durationMillisAlpha: Int = durationMillis / 2,<br>    easing: Easing = EaseOutBack,<br>    alphaEasing: Easing = LinearEasing,<br>    offsetDp: Dp = 12.dp,<br>    placementDelayMillis: Long = 0L,<br>    onAnimationFinished: () -&gt; Unit = {}<br>): Modifier = composed {<br><br>    val scope = rememberCoroutineScope()<br>    val anim = remember { Animatable(1f) }<br>    val alphaAnim = remember { Animatable(0f) }<br>    var dimension by remember { mutableIntStateOf(0) }<br>    val density = LocalDensity.current<br><br>    this<br>        .onPlaced {<br>            dimension = with(density) { offsetDp.roundToPx() }<br><br>            if (anim.value == 1f) {<br>                scope.launch {<br>                    delay(placementDelayMillis)<br>                    anim.animateTo(<br>                        targetValue = 0f,<br>                        animationSpec = tween(durationMillis, easing = easing)<br>                    )<br>                    onAnimationFinished()<br>                }<br>                scope.launch {<br>                    delay(placementDelayMillis)<br>                    alphaAnim.animateTo(<br>                        targetValue = 1f,<br>                        animationSpec = tween(durationMillisAlpha, easing = alphaEasing)<br>                    )<br>                }<br>            }<br>        }<br>        .offset {<br>            when (animationDirection) {<br>                AnimationDirection.UP -&gt; IntOffset(<br>                    x = 0,<br>                    y = (dimension * anim.value).toInt()<br>                )<br><br>                AnimationDirection.DOWN -&gt; IntOffset(<br>                    x = 0,<br>                    y = -(dimension * anim.value).toInt()<br>                )<br><br>                AnimationDirection.LEFT -&gt; IntOffset(<br>                    x = (dimension * anim.value).toInt(),<br>                    y = 0<br>                )<br><br>                AnimationDirection.RIGHT -&gt; IntOffset(<br>                    x = -(dimension * anim.value).toInt(),<br>                    y = 0<br>                )<br><br>                AnimationDirection.SCALE_IN -&gt; IntOffset.Zero<br>                AnimationDirection.SCALE_OUT -&gt; IntOffset.Zero<br>            }<br>        }<br>        .graphicsLayer {<br>            val scale = when (animationDirection) {<br>                AnimationDirection.SCALE_IN -&gt; 1f - anim.value<br>                AnimationDirection.SCALE_OUT -&gt; anim.value<br>                else -&gt; 1f<br>            }<br>            scaleX = scale<br>            scaleY = scale<br>            alpha = alphaAnim.value<br>        }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=445da4998031" width="1" height="1" alt=""><hr><p><a href="https://medium.com/tilt-engineering/android-ui-staggered-enter-animation-445da4998031">Android UI: Staggered enter animation</a> was originally published in <a href="https://medium.com/tilt-engineering">Tilt Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blast Off: Managing Hundreds of UI Updates for an Emoji Cannon]]></title>
            <link>https://proandroiddev.com/blast-off-managing-hundreds-of-ui-updates-for-an-emoji-cannon-37ecb25c2e88?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/37ecb25c2e88</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Sat, 08 Jul 2023 00:17:24 GMT</pubDate>
            <atom:updated>2023-07-08T00:17:24.363Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jLGbiV71l2gdKe6j" /><figcaption>Photo by <a href="https://unsplash.com/@countchris?utm_source=medium&amp;utm_medium=referral">Count Chris</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Managing the state can be a challenge. Managing the state with hundreds of updates and constant recomposition of floating emojis is a challenge indeed. In this blog post, I’ll share how to build an emoji cannon that floods your screen with UI elements. We’ll look at how to update the state without freezing your UI. All with Jetpack Compose 🧑🏼‍🎨</p><h3>Building a cannon 💥</h3><p>Our goal here is to build a simple UI, starting with a button and an empty screen. Every time the user clicks the button we should fire an emoji in the air(screen) and clean it after a while with a fadeOut() exit animation. Here is the final result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/0*K6I0N3SbplFJnOOR.gif" /><figcaption>Emoji cannon, sending random emoji on each button click</figcaption></figure><p>Let’s look at the parts of the effect one by one:</p><ul><li>the animation starts at the bottom of the screen, in the middle</li></ul><pre>val configuration = LocalConfiguration.current<br>val startPoint = IntOffset(<br>    x = configuration.screenWidthDp / 2,<br>    y = (configuration.screenHeightDp * 0.9f).toInt()<br>)</pre><ul><li>each emoji has a different end position, restricted by a Y-coordinate (0-20% of the screen height) and an X-coordinate(0–100% of the screen width)</li></ul><pre>val width = LocalConfiguration.current.screenWidthDp<br>val height = LocalConfiguration.current.screenHeightDp<br>val targetX = Random.nextInt(0, width)<br>val targetY = Random.nextInt(0, (height * 0.2).toInt())</pre><ul><li>random rotation is applied in the range of -90 deg, 90 deg (3)</li></ul><pre>val rotation = Random.nextInt(-90, 90).toFloat()</pre><ul><li>emojis fade out slowly after they reach their target position</li></ul><pre>val opacityAnimatable = remember { Animatable(0f) }<br>val offsetXAnimatable = remember { Animatable(startPoint.x, Int.VectorConverter) }<br>val offsetYAnimatable = remember { Animatable(startPoint.y, Int.VectorConverter) }<br>val rotationAnimatable = remember { Animatable(0f) }</pre><p>For each variable, I have created separate Animatable values, with specific initials. In LaunchedEffect , all the animations are called to animate to the target values specified by Random functions.</p><pre>LaunchedEffect(Unit) {<br>    val opacity = async { opacityAnimatable.animateTo(1f, animationSpec = tween(500)) }<br>    val offsetY =<br>        async { offsetYAnimatable.animateTo(item.offsetY, animationSpec = tween(1000)) }<br>    val offsetX =<br>        async { offsetXAnimatable.animateTo(item.offsetX, animationSpec = tween(1000)) }<br>    val rotation = async { rotationAnimatable.animateTo(1f, animationSpec = tween(1000)) }<br>    awaitAll(offsetX, offsetY, rotation, opacity)<br>    opacityAnimatable.animateTo(0f, animationSpec = tween(2000))<br>}</pre><p>The awaitAll is used here to make sure all animations are finished and our Emoji is now in the final position. After that, we can start the slow fade out by calling: opacityAnimatable.animateTo.</p><p>All the variables are applied to a simple Box and the emoji is a Text composable with a Unicode value for an emoji.</p><pre>Box(<br>    modifier = Modifier<br>        .offset(<br>            x = offsetXAnimatable.value.dp, <br>            y = offsetYAnimatable.value.dp)<br>        .rotate(rotationAnimatable.value.times(rotation))<br>        .alpha(opacityAnimatable.value)<br>) {<br>    Text(text = &quot;\uD83D\uDE00&quot;, fontSize = 40.sp)<br>}</pre><h3>Managing the recompositions</h3><p>Single-type events were always tricky in Android views. Nowadays with Jetpack Compose things get even harder when everything on-screen needs to be a reflection of a state. How to build a state of something that is temporary and its visibility is controlled by the duration of animations?</p><p>To start, let&#39;s try to display multiple items just using a list. To have all parameters in one place I introduced the data class MyEmoji</p><pre>data class MyEmoji(<br>    val rotation: Float,<br>    val offsetX: Int,<br>    val offsetY: Int,<br>    val unicode: String = emojiCodes.random()<br>)</pre><p>Every time a user clicks the button we will put a new item into the list.</p><pre>val emojis = remember { mutableStateListOf&lt;MyEmoji&gt;() }<br><br>Button(<br>    modifier = Modifier.align(Alignment.BottomCenter),<br>    onClick = {<br>        emojis.add(<br>            MyEmoji(<br>                rotation = Random.nextInt(-90, 90).toFloat(),<br>                offsetX = Random.nextInt(0, width),<br>                offsetY = Random.nextInt(0, (height * 0.2).toInt())<br>            )<br>        )<br>    }) {<br>    Text(text = &quot;FIRE!!&quot;)<br>}<br><br>// Show emoji on screen<br>emojis.forEach { emoji -&gt;<br>    SingleEmojiContainer(item = emoji)<br>}</pre><p>Run this code on an emulator and you will see that everything works. Our job ends here. Or does it? Let’s double-check the recomposition count using the Layout Inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdqSysSjZE6Bz-gRyjXywA.png" /></figure><p>Hitting the button just once results in 174 recompositions. That is not right. Let&#39;s try to fix that by applying some changes based on this article: <a href="https://medium.com/androiddevelopers/jetpack-compose-debugging-recomposition-bfcf4a6f8d37">https://medium.com/androiddevelopers/jetpack-compose-debugging-recomposition-bfcf4a6f8d37</a></p><p>I can change the offset it to its lambda version, but rotation and alpha do not have an equivalent. Luckily graphicsLayer {} comes to the rescue and just like that we have all the animation parameters in lambdas.</p><pre>Box(<br>    modifier = Modifier<br>        .offset {<br>            IntOffset(<br>                x = offsetXAnimatable.value.dp.roundToPx(),<br>                y = offsetYAnimatable.value.dp.roundToPx()<br>            )<br>        }<br>        .graphicsLayer {<br>            rotationZ = rotationAnimatable.value.times(item.rotation)<br>            alpha = opacityAnimatable.value<br>        }<br>) {<br>    Text(text = item.unicode, fontSize = 40.sp)<br>}</pre><p>Check the Layout Inspector now 👇</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxwJX3xmsd-4JFGNfNTnpg.png" /></figure><p>Applying these changes we manage to get rid of those crazy recompositions. However, there are some leftovers. In the above screenshot, you can see there are 5 emojis on the screen. These are not visible to the user as their alpha is 0f, but they are still there. Sitting quietly and skipping compositions. If you wonder why they skip recomposition, you can find the answer here: <a href="https://developer.android.com/jetpack/compose/lifecycle#skipping">https://developer.android.com/jetpack/compose/lifecycle#skipping</a>.</p><p><strong><em>TL;DR</em></strong><em>: If you use </em><em>@Stable class, primitives, or Strings, the recomposition may be skipped if applicable.</em></p><h3>Remove from list</h3><p>When you have just a few elements floating on the screen that are invisible, you would not care too much. Adding a new element to the list and forgetting about it, even if it does not feel right, will work. However, having thousands of these elements might cause some issues, such us:</p><ul><li>Skipped 728 frames! The application may be doing too much work on its main thread.</li><li>Davey! duration=12559ms; Flags=0, FrameTimelineVsyncId=11941972,</li><li>Background concurrent copying GC freed 504936(13MB) AllocSpace objects, 13(10MB) LOS objects, 21% free, 86MB/110MB, paused 1.212s,11us total 12.149s</li></ul><p>All the above means we are doing too much on the main thread and our app is skipping frames, freezing, and pausing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NeBkp-u4tA-yv0FrYHz7A.png" /><figcaption>Memory footage from Android Profiler</figcaption></figure><p>The memory footage from the profiler doesn&#39;t look good either. The emojis are not removed and memory is not freed.</p><p>It is clear that we have some issues and we need to handle this list better. Let&#39;s remove the item from the list when fadeOut() ends.</p><pre>LaunchedEffect(Unit) {<br>    . . .<br>    awaitAll(offsetX, offsetY, rotation, opacity)<br>    opacityAnimatable.animateTo(0f, animationSpec = tween(2000))<br>    onAnimationFinished()<br>}<br><br>SingleEmojiContainer(item = emoji, onAnimationFinished = { emojis.remove(emoji) })</pre><p>Here is the recording with this change:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*clDJyqmD2Z8Yc09Vq3ZojQ.gif" /></figure><p>That is unfortunate. What is happening? The list of emojis is edited during the animation, so all the elements are recomposed. It switches the emojis every time we call remove on the snapshotList .</p><p>To fix that we need to wrap the SingleEmojiContainer with the utility function key{}. This prevents more than one execution during composition. The key{} function needs a local unique key that will be compared to the previous invocation and stop unwanted recomposition.</p><p>Whenever the button is clicked, a new emoji object is created and we need to ensure it has a unique key. For that purpose, I will use random UUID: id = UUID.randomUUID().toString(). Here is the updated MyEmoji data class:</p><pre>data class MyEmoji(<br>    val id: String,<br>    val rotation: Float,<br>    val offsetX: Int,<br>    val offsetY: Int,<br>    val unicode: String = emojiCodes.random()<br>)</pre><p>And updated code for displaying the emojis:</p><pre>emojis.forEach { emoji -&gt;<br>    key(emoji.id) {<br>        SingleEmojiContainer(item = emoji, onAnimationFinished = { emojis.remove(emoji) })<br>    }<br>}</pre><p>Here is the layout inspector, profiler data, and resulting video.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM0BCEL7Bvwk88Dpa7NQuw.png" /></figure><p>The SingleEmojiContainer does not recompose at all. The FireButton skips recomposition as many times as it animates, since we have a ripple effect on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nh9Vy0fD-Ts8Yk6CPEZ-1w.png" /></figure><p>The memory management is now correct. After the animation ends, the memory is freed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/0*K6I0N3SbplFJnOOR.gif" /><figcaption>Emoji cannon, sending random emoji on each button click</figcaption></figure><h3>Updating from ViewModel — production example</h3><p>At <a href="https://tilt.app/">Tilt</a>, we display each emoji sent by a viewer on the screen. They appear on both sides of the screen, with added transparency, random path, and delays, so as not to interfere with the streaming experience, but to show the activity of other participants.</p><p>To solve this use case, we moved the list management into viewModel.</p><ul><li>Firstly, store the set of pairs in ViewModel with an emoji symbol and unique ID: Set&lt;Pair&lt;String, String&gt;&gt; . This set represents the emojis that are currently visible on the screen, but it does not know anything about the progress of animation, rotation, alpha, etc.</li></ul><pre>private val _viewersReactions = MutableStateFlow&lt;Set&lt;Pair&lt;String, String&gt;&gt;&gt;(setOf())<br>val viewersReactions: StateFlow&lt;Set&lt;Pair&lt;String, String&gt;&gt;&gt;<br>    get() = _viewersReactions<br><br>// Called from view when emoji is displayed, to delete it from the VM list<br>fun updateViewersReactions(pair: Pair&lt;String, String&gt;) = viewModelScope.launch {<br>    _viewersReactions.update { oldSet -&gt; oldSet - pair }<br>}</pre><ul><li>Then, in the view, we create an emoji state object that has all the info about startPoint, endPoint, rotation, etc. Every time the emoji ends the animation, the high-order function gets called to inform VM that this element is no longer visible. We pass the unique ID to make sure the proper element from the set will be removed.</li></ul><pre>viewersReactions.forEach { pair -&gt;<br>    key(pair.second) {<br>        RoomViewerEmojiReaction(<br>            emoji = pair.first,<br>            path = EmojiUtils.getRandomViewerPath(),<br>            modifier = Modifier.align(Alignment.BottomStart),<br>            onAnimationFinished = {<br>                // Inform VM that this emoji was displayed<br>                viewerEmojiFired(pair)<br>            }<br>        )<br>    }<br>}</pre><p>The final result from the Tilt app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*xcD01_KS5T4_mq183qySUA.gif" /><figcaption>Tilt scheduled room with viewer&#39;s emojis</figcaption></figure><h3>Epilogue</h3><p>For those of you that just scrolled to the bottom, here are the key takeaways:</p><ul><li>use lambda versions of modifiers that change the layout properties like alpha, rotation, position, scale, etc. You will avoid unnecessary recompositions</li><li>use the key{} utility function in Composable to avoid extra recompositions</li><li>remove items from the list if they are no longer visible to free up memory</li></ul><p>For those of you that read this blog post, thank you. It was not a quicky. If you have any comments or questions, do not hesitate to reach out using Medium or <a href="https://twitter.com/piotr_prus">Twitter</a>.</p><p><em>Big thanks to </em><a href="https://twitter.com/MatthewCallery"><em>Matt Callery</em></a><em> 👏 for the initial version of the code, path randomizer, and proofreading of this blog post.</em></p><p>Happy composing 🎹 👨🏼‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37ecb25c2e88" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/blast-off-managing-hundreds-of-ui-updates-for-an-emoji-cannon-37ecb25c2e88">Blast Off: Managing Hundreds of UI Updates for an Emoji Cannon</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[Not only modifiers can be easily modified in Jetpack Compose]]></title>
            <link>https://piotrprus.medium.com/not-only-modifiers-can-be-easily-modified-in-jetpack-compose-cb0ac4b418b7?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/cb0ac4b418b7</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Wed, 14 Jun 2023 20:16:49 GMT</pubDate>
            <atom:updated>2023-06-14T20:16:49.467Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qeG1WU4lL4gAiq3w" /><figcaption>Photo by <a href="https://unsplash.com/@tolga__?utm_source=medium&amp;utm_medium=referral">Tolga Ulkan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I bet everyone that use Jetpack Compose for a while knows that making a custom modifier is not only possible, but also very easy and helpful, but did you know you can make your own Alignment for Row/Column? During my Jetpack Compose exploration, I found that you can customize basically everything and in this blog post, I will show you one cool example.</p><h3>The challenge</h3><p>I needed to present items in a row that are equally distributed from their centers, not having even spacing between them. The below graph presents the problem. The red crossbars represent equal spacing. The green crossbars have slightly different lengths. Our goal is to make green crossbars equal in length.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CO-YbK7EUcnhrZIGH3hELg.png" /></figure><h3>Arrangement.SpaceEvenly</h3><p>The closest arrangement to this in question is Arrangement.SpaceEvenly. Let’s check the code for it:</p><pre>@Stable<br>val SpaceEvenly = object : HorizontalOrVertical {<br>    override val spacing = 0.dp<br><br>    override fun Density.arrange(<br>        totalSize: Int,<br>        sizes: IntArray,<br>        layoutDirection: LayoutDirection,<br>        outPositions: IntArray<br>    ) = if (layoutDirection == LayoutDirection.Ltr) {<br>        placeSpaceEvenly(totalSize, sizes, outPositions, reverseInput = false)<br>    } else {<br>        placeSpaceEvenly(totalSize, sizes, outPositions, reverseInput = true)<br>    }<br><br>    override fun Density.arrange(<br>        totalSize: Int,<br>        sizes: IntArray,<br>        outPositions: IntArray<br>    ) = placeSpaceEvenly(totalSize, sizes, outPositions, reverseInput = false)<br><br>    override fun toString() = &quot;Arrangement#SpaceEvenly&quot;<br>}</pre><p>The main function that does the placement magic here is Density.arrange , followed by placeSpaceEvenly.</p><pre>internal fun placeSpaceEvenly(<br>    totalSize: Int,<br>    size: IntArray,<br>    outPosition: IntArray,<br>    reverseInput: Boolean<br>) {<br>    val consumedSize = size.fold(0) { a, b -&gt; a + b }<br>    val gapSize = (totalSize - consumedSize).toFloat() / (size.size + 1)<br>    var current = gapSize<br>    size.forEachIndexed(reverseInput) { index, it -&gt;<br>        outPosition[index] = current.roundToInt()<br>        current += it.toFloat() + gapSize<br>    }<br>}</pre><p>Breaking this 👆code line by line:</p><ul><li>consumedSize sums all the sizes of child items</li><li>gapSize takes the totalSize of the parent, subtracts the size of the children, and divides the result by the number of elements plus 1. This equation gives us an equal gap to apply to the layout</li><li>Lastly, for each element, we specify the new position by adding a gap to our position of the element</li></ul><p>It does not look complicated, right? Let&#39;s make our custom Arrangement object.</p><h3>Spread over center</h3><p>I will call the custom arrangement: Arrangement.SpreadOverCenter and extend it with Arrangement.Horizontal. As in the above example, I will need to override the function arrange().</p><pre>fun Arrangement.SpreadOverCenter(minSpace: Dp = 0.dp): Arrangement.Horizontal =<br>    object : Arrangement.Horizontal {<br>        override val spacing: Dp<br>            get() = minSpace<br><br>        override fun Density.arrange(<br>            totalSize: Int,<br>            sizes: IntArray,<br>            layoutDirection: LayoutDirection,<br>            outPositions: IntArray<br>        ) {<br>            // Our code goes here<br>        }<br><br>        override fun toString() = &quot;Arrangement#spreadOverCenter($minSpace)&quot;<br>    }</pre><pre>override fun Density.arrange(<br>    totalSize: Int,<br>    sizes: IntArray,<br>    layoutDirection: LayoutDirection,<br>    outPositions: IntArray<br>) {<br>    if (sizes.isEmpty()) return<br>    val firstWidth = sizes.first()<br>    val lastWidth = sizes.last()<br>    val equalSpace = (totalSize - firstWidth.div(2) - lastWidth.div(2)).div(<br>        (sizes.size.minus(1).coerceAtLeast(1))<br>    )<br>    sizes.forEachIndexed { index, size -&gt;<br>        outPositions[index] = firstWidth.div(2) + equalSpace * index - size.div(2)<br>    }<br>}</pre><p>Arranging the positions step by step:</p><ol><li>I am checking if sizes are not empty and returning the function otherwise.</li><li>I assign two values for the first and the last element width.</li><li>To calculate the equalSpace, I am taking the totalSize of the parent row, subtracting half of the first and half of the last width, and dividing the result by the number of elements minus 1.</li><li>Having calculated the space(gap) I can now apply the new position to each element by multiplying the gap and subtracting half of the element size. Voila, we arrange the elements of a row with a custom arrangement object.</li></ol><h3>The result</h3><p>Here is the final result for boxes with different sizes. The first row presents the same layout positioned using Arrangement.SpaceEvenly. The second row is built using custom Arrangement.SpreadOverCenter</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*X2DWFHI7ZfZf1i2I8kLkiA.png" /></figure><p>As you can see the Composable Modifier is not the only object that can be easily customized. I encourage you to experiment not only with Arrangement but with all the different objects and factors that are used to position the layout. Happy composing! 🎹 👨🏼‍💻</p><p><em>Thanks, </em><a href="https://medium.com/u/3723c77a132f"><em>Damian Petla</em></a><em> for the review</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cb0ac4b418b7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exposing the separate resources module to iOS target using moko-resources in KMM]]></title>
            <link>https://proandroiddev.com/exposing-the-separate-resources-module-to-ios-target-using-moko-resources-in-kmm-76b9c3d533?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/76b9c3d533</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Sat, 14 May 2022 17:28:47 GMT</pubDate>
            <atom:updated>2022-05-16T12:21:18.086Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9uj6jAbBX1wCYq1M" /><figcaption>Photo by <a href="https://unsplash.com/@thetechnomaid?utm_source=medium&amp;utm_medium=referral">Sophie Elvis</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In Android development, modularization of the application is a very common pattern that helps organize the code, increase the readability and make sharing between projects more straightforward. Some say it also decreases the build time, but this is not a part of this article. If you would like to learn more, check out <a href="https://youtu.be/PZBg5DIzNww">this video</a> from Google I/O’19.</p><h3>Why make a separate module for resources?</h3><p>Whenever your modules are features or layers based, the resources like localized texts or icons can be used anywhere in the app UI and reused in many modules. Now when compose is becoming a standard we can create UI-only modules with compose dependencies and app resources. The composables do not need to know about any business class.</p><p>In the KMM project, the additional benefit can be seen while importing the module. Having the resources independently, the iOS view class will import only this. Same on the Android side, the common module for a ui-only module will not be needed.</p><h3>Multiplatform resources</h3><p>For my KMM projects, I use <a href="https://github.com/icerockdev/moko-resources">moko-resources</a>. The library from icerock devs provides access to resources on different platforms with the support of the default system localization.</p><p>Let’s implement it step by step:</p><ul><li>create a separate module for resources:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*ugQabCsLwFNiHK6_k31NwQ.png" /></figure><ul><li>build.gradle needs to include the icerock plugin dev.icerock.mobile.multiplatform-resources and an extension function multiplatformResources that will generate the resources classes. Also, we need to add api keyword to the library dependency (<a href="https://gist.github.com/PiotrPrus/e851444537a50d32c2bd03cd063e0a5e">A gist with a full example</a>)</li></ul><pre>plugins {    <br>kotlin(&quot;multiplatform&quot;)    <br>id(&quot;com.android.library&quot;)                    id(&quot;dev.icerock.mobile.multiplatform-resources&quot;)<br>}</pre><ul><li>After adding the resources to commonMain/resources/MR/base we should be ready to go to use them everywhere. Disclaimer: Pay attention to the resources directory name. Even if we choose the custom name, the directory needs to be named MR</li><li>At this point, Android works after importing the new resources module, but iOS does not see it in the generated framework. Why?</li></ul><h3>Exposing the shared resources to the iOS framework</h3><p>The iOS target depends on KMM import which in my case is shared. I didn’t want to add an extra framework for iOS colleagues, so I needed to expose the resources to the common module. In order to do that we need to modify build.gradle of the shared module.</p><ul><li>include the icerock plugin dev.icerock.mobile.multiplatform-resources and an extension function multiplatformResources that will generate the resource classes. Also, we need to add api library dependency.</li></ul><p>Sounds familiar? This is exactly the same step that we did for the shared resources module before. Check this gist to identify changes in kotlin { } block.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f95750a70bc7fa147261f6998c8069a/href">https://medium.com/media/3f95750a70bc7fa147261f6998c8069a/href</a></iframe><p>The framework that will be generated for the iOS target needs sharedResources to be exported together with moko-resources dependency. The first one will contain generated classes while the other is allowing the iOS to use a specific library API. Together with the plugin installed and extension function in the common module, this project will build iOS, without any change from iOS devs required.</p><p>I believe Kotlin Multiplatform is the framework that will be widely used in the mobile world. The reason is, that the KMM is optional and every team can start testing it and implement only a part of it. The resources are a perfect example of how KMM can reduce the amount of duplicated code on mobile platforms.</p><p>Big thanks to <a href="https://medium.com/u/ff07a262acb5">Carlos Mota</a> for the review 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=76b9c3d533" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/exposing-the-separate-resources-module-to-ios-target-using-moko-resources-in-kmm-76b9c3d533">Exposing the separate resources module to iOS target using moko-resources in KMM</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[Interacting with Composable Canvas]]></title>
            <link>https://proandroiddev.com/interacting-with-composable-canvas-4a21fa780ce7?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a21fa780ce7</guid>
            <category><![CDATA[canvas]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Fri, 31 Dec 2021 14:43:32 GMT</pubDate>
            <atom:updated>2022-01-03T20:01:29.562Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*P4t2Jm38zBwUOXt9" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I need to admit, I totally fall in love with Jetpack Compose. Compose gives me a lot of joy, I never felt so confident with creating views. I always liked to make custom views and even more custom views with custom behaviors like gestures or/and animations. I was really happy when the designer came with a new mockup for bar charts. I already planned how to do that in Compose. Here is the design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*z8Iazh_wK5_ul_sChQqEAg.gif" /><figcaption>Interactive bar chart. Tap selects bar, long click pre-selects</figcaption></figure><h3>Composable Lazy Row</h3><p>Firstly I thought that it will work nicely as a LazyRow with simple Boxes. Box for gradient background, Box for actual Bar, and Text Composable for value above each bar. Unfortunately, there were some performance issues. Too many of those were on one screen and I was losing frames. The swipe gesture did not work smoothly.</p><h3>Composable Canvas</h3><p>This time, there was no performance issue at all, but I didn’t know how to do it interactively, let alone control states for the selected option and the temporary select. I will not write down how to create a bar chart using canvas, it is not a part of this article. I will focus on the interactive part and state management.</p><h4>Make Canvas react to gestures</h4><p>Initially, I needed a way to detect gestures on my canvas. Modifier.pointerInput appeared with a helping hand. This function creates a modifier for processing user input within the region of the modified element. Underneath it runs LauncherEffect with a coroutine scope for the chosen key. We just need to wait for the appropriate event to show up. Let’s see how we can use it in our own Composable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0efc1209c229e403d3f5aace22d829d4/href">https://medium.com/media/0efc1209c229e403d3f5aace22d829d4/href</a></iframe><ul><li>MutableInteractionSource<em> </em>allows listening to interaction changes inside components.</li><li>AwaitPointerEventScope<em> </em>suspends and installs a pointer that can await events and react to them immediately.</li></ul><p>At this point (line 11) we can call our onStart function. The event has started. Now, it would be nice to know how and when it will end. Below you can find the extended version of startGesture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/099cde6eaa847295d8052c3e0bebf904/href">https://medium.com/media/099cde6eaa847295d8052c3e0bebf904/href</a></iframe><p>This modifier can track the start, the end, and cancellation of the gesture. I added xPosition to each of the high order functions, to keep track of the pointer position and cancel the selection only if it exceeds the bounds.</p><h4>Check which bar has been selected</h4><p>To manage which bar has been touched, I’ve created a helper data class with fields: xStart, xEnd, index. For the purpose of this article, let’s assume that the distance between bars is 20px. I mapped all the elements of the list into my helper class and calculate the start and end positions for each of them.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4b775af6c02cc5f7681be14fa303d8e/href">https://medium.com/media/d4b775af6c02cc5f7681be14fa303d8e/href</a></iframe><p>With that prepared list, we can easily determine with which element the user interacts.</p><h4>Simple select</h4><p>For this scenario, we just need to know at what position the user ended(completed) the touch event. At this point, we should check if the position is in the range of one of the bars.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a08d1251c353819fa8d733c184cd5ee9/href">https://medium.com/media/a08d1251c353819fa8d733c184cd5ee9/href</a></iframe><p>Every change of selectedPosition or barAreas will trigger the change for the selected bar. The selected position is changed in onCompleted.</p><p>I was struggling a bit about choosing the right animation API, but I found this flowchart in <a href="https://developer.android.com/jetpack/compose/animation">the documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t6EI70xMNKRdojHdXIK95g.png" /><figcaption>Jetpack Compose animation flowchart</figcaption></figure><p>Since the animation is my source of truth, I choose the Animatable. Animatable creates a float value holder that automatically changes its value when we call .animateTo. Here is the implementation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9beacfaf571ca4c1ea93298252a51af5/href">https://medium.com/media/9beacfaf571ca4c1ea93298252a51af5/href</a></iframe><h3>Manage two selections</h3><p>The example presented at the beginning of this blog post shows two available states for each bar: pressed and focused. For better user experience, we decided to hold two states for the chart. Each bar can be focused, which does not guarantee it will be selected. In order to manage those states, we need to clone the following variables: selectedPosition, selectedBar, and animatable. I added the temp prefix for those clones. Let’s go for pseudo code to have some basic idea of how this will work.</p><pre>gestureStarted()<br>// at this point we do not know how this gesture will end, so we can start animation of tempSelection<br>tempSelection = xPosition<br>tempAnimatable.animateTo(1)<br>---<br>gestureCanceled()<br>// user decided to cancel the gesture, we need to reset the selection and animation back to 0<br>tempSelection = -1<br>tempAnimatable.animateTo(0)<br>---<br>gestureCompleted()<br>// user finishes the click event, we need to assign values from temporary to main. If the animation was not finished at that point, it should take the value from temp and continue the animation till 1 as a final result.<br>animatable = tempAnimatable + animateTo(1)<br>tempAnimatable = 0<br>selection = tempSelection<br>tempSelection = -1</pre><p>Here is the implementation. Most happens in onCompleted function. These two asynchronous functions are important to note:</p><ol><li>(line 31)The duration of finishing animation is calculated from temporary animation progress (1f — tempAnim.value)</li><li>(line 37) In order to animate deselection, we need to firstly select it and then animate the value towards 0f.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14fd5b7955fbfde41539ff92dcff5b17/href">https://medium.com/media/14fd5b7955fbfde41539ff92dcff5b17/href</a></iframe><h3>Testing</h3><p>Compose testing library provides an easy-to-read API to find elements, interact with them and verify. UI tests in compose use <em>Semantics </em>to interact with UI hierarchy. If you want to learn more, <a href="https://developer.android.com/jetpack/compose/testing">here is a good article</a>.</p><p>There are two important things that we will add to make testing simpler, more readable. Firstly, I have moved bar selection outside of composable to have fine control from the parent and make testing easier. This pattern is called state hoisting, read more about it <a href="https://developer.android.com/jetpack/compose/state#state-hoisting">here</a>.</p><pre>@Composable<br>fun BarChartCanvas(list: List&lt;Int&gt;, barSelected: (Int) -&gt; Unit)</pre><p>Secondly, to make our search in UI hierarchy easier, we will add testTag to the canvas modifier.</p><pre><em>Row</em>(<br>    Modifier<br>        .<em>fillMaxWidth</em>()<br>        .<em>padding</em>(12.<em>dp</em>)<br>        .<em>height</em>(150.<em>dp</em>)<br>        .<em>testTag</em>(&quot;BarChart&quot;)<br>        .<em>horizontalScroll</em>(<em>rememberScrollState</em>())</pre><p>Let&#39;s create the first test, just to check the canvas existence.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86edb75c407c943f0a125facaf149cfb/href">https://medium.com/media/86edb75c407c943f0a125facaf149cfb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*2Idmi539ninxOVZ8n-j2sg.png" /></figure><p>The test passes, the BarChartCanvas exists on the screen, now we can create a more demanding test. We will check if clicking at a given position will select the correct bar. Before I will show you the code, here are some important information:</p><ol><li>Selection width is 20.dp</li><li>Horizontal start/end padding is 12.dp</li><li>Initially, the first element of the chart is selected</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f91b2f8cdbde24f77691ab280edda365/href">https://medium.com/media/f91b2f8cdbde24f77691ab280edda365/href</a></iframe><p>The distance (x position) is calculated as a sum of start padding and 3 times selection width. To convert the dp values to px , we can use composeTestRule.density. It works the same like Composable <em>LocalDensity.current. </em>Explaining the 9 and 10 lines of the snipped: onNodeWithTag is looking for our BarChart then we perform the click gesture at the calculated x position.</p><p>This action should result in changing the selectedItem to the third element, which has the value of 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*r3GfOpekO_Je81vuwc1GZA.png" /></figure><p>The last test that I want to perform is canceling the selection. Think about the following scenario: the user clicks on Bar, but instead of releasing the pointer, swipes horizontally. Such a gesture should cancel the selection.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d7764897097c05bcab1785eb4b52ec8/href">https://medium.com/media/4d7764897097c05bcab1785eb4b52ec8/href</a></iframe><p>This test looks similar to the previous, but instead of a simple click gesture, we are performing 3 gestures: pointer down, move, and up. This gesture should not result in invoking onComplete from our tapOrPress modifier, so the third element shouldn’t be selected. Since the initial selection is element 1, we are checking this value in <em>assertEquals.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*p5oYBTOeWiohqv2bVz2j9A.png" /></figure><h3>Final thoughts</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*z8Iazh_wK5_ul_sChQqEAg.gif" /><figcaption>Interactive bar chart. Tap selects bar, long click pre-selects</figcaption></figure><p>In my opinion, creating custom views in android has never been easier. Jetpack Compose provides a really refreshing experience to android development. Managing the state of selection and animation is straightforward and very readable. If I were to create a similar interactive graph using XML, I would probably reach for a ready-made library.</p><p>Thanks, <a href="https://medium.com/u/3723c77a132f">Damian Petla</a> for the review.</p><p>If you have any questions or comments, please use reply or reach me on <a href="https://twitter.com/piotr_prus">Twitter</a>.</p><p>Happy composing! 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a21fa780ce7" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/interacting-with-composable-canvas-4a21fa780ce7">Interacting with Composable Canvas</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[Publishing KMM swift package using GitHub actions.]]></title>
            <link>https://piotrprus.medium.com/publishing-kmm-swift-package-using-github-actions-5f1d4d03c962?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f1d4d03c962</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kmm]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[multiplatform]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 10:06:56 GMT</pubDate>
            <atom:updated>2021-12-08T08:39:43.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-p2vbVX4C7aj19qg" /><figcaption>Photo by <a href="https://unsplash.com/@jiaweizhao?utm_source=medium&amp;utm_medium=referral">Jackie Zhao</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When you use Kotlin Multiplatform Mobile, there are two ways you can use the shared module. The first method is to have the shared module within the one repository with client apps(android and iOS), and the second one is to have all the parts separately, each in a different git repository. The second option scales better for bigger apps and distributed teams. This is the one that we choose for a recent project and I will write about its configuration n this blog post.</p><h3>Swift package</h3><p>To use shared module code in swift, we need to distribute/publish a framework that can be consumed by the Xcode. My iOS teammates asked specifically about Swift Package, which is a relatively new technology. Thankfully, I found <a href="https://johnoreilly.dev/posts/kotlinmultiplatform-swift-package/">this article</a> by <a href="https://twitter.com/joreilly">John O’Reilly</a> that sheds light on the matter.</p><p>To make a swift package, I will use the <a href="https://github.com/ge-org/multiplatform-swiftpackage">Multiplatform swift package</a> Gradle plugin. After setting this up, we can run the command:</p><pre>./gradlew createSwiftPackage</pre><p>that will create the framework, ready to use in our iOS project. Let’s jump into the CD setup to never worry about this again and just focus more on development 💻.</p><h3>Publishing the framework</h3><p>This should be fairly easy , I told myself and start looking into documentation and examples. I found this article, with a very promising title: <a href="https://github.blog/2019-06-03-github-package-registry-will-support-swift-packages/">GitHub Package Registry will support Swift package</a>. Although, the post is from June 2019, the support for Swift Package is not here yet. There is an ongoing discussion on this <a href="https://forums.swift.org/t/swift-package-registry-service/37219">forum</a> if you would like to learn more.</p><p>One of the methods for publishing the swift package is the separate repository. Adding package dependency to Xcode is well supported and described on the <a href="https://developer.apple.com/documentation/swift_packages/adding_package_dependencies_to_your_app">Apple developer site</a>. Let’s see how to do it using GitHub actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/427df25633928859ae649ad29c67e1f6/href">https://medium.com/media/427df25633928859ae649ad29c67e1f6/href</a></iframe><p>The above workflow will build the Swift Package in shared/swiftpackage. To send all the files from that directory to a separate repository we will use action from the GitHub marketplace. It has a very descriptive name: <a href="https://github.com/cpina/github-action-push-to-another-repository">Push to another repository</a>. There are a few requirements to meet:</p><ul><li>The destination repository needs to exist already</li><li>The destination branch needs to exist already</li><li>We need to provide a GitHub token that has permission to write to the destination repository</li><li>The action runs only on a Linux server. macOS is not supported / <a href="https://github.com/cpina/github-action-push-to-another-repository/issues/36">issue</a></li></ul><p>To fulfill the first three requirements, we can create the repository with the main branch and copy the token to GitHub secrets. We will automate it later, but now let’s deal with the last requirement.</p><p>The Linux server does not have an access to MacOS outputs, so we need to upload our artifacts and download these on another server. Hopefully, there are two perfect actions that do exactly that, <a href="https://github.com/actions/upload-artifact">upload</a> and <a href="https://github.com/actions/download-artifact">download</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/724d24288d2ef34bcfe09a960bdb81d5/href">https://medium.com/media/724d24288d2ef34bcfe09a960bdb81d5/href</a></iframe><p>Now, with Swift Package in place, on right server, we can upload it to other repository.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0e9dd6f710df614350107a906581de5/href">https://medium.com/media/e0e9dd6f710df614350107a906581de5/href</a></iframe><h3>Push to a specific custom-named branch</h3><p>The above-presented solution works smoothly but supports only main branch. It is good to have a history of the packages and the ability to make alpha and release branches.</p><p>To automatically create a branch on different repo we can use this action: <a href="https://github.com/GuillaumeFalourd/clone-github-repo-action">Clone GitHub repo</a>. The action allows us to create a new branch and the only requirement to do that is providing the GitHub token that we already use for previous actions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d818a173c995aafecdcd8532334719a/href">https://medium.com/media/3d818a173c995aafecdcd8532334719a/href</a></iframe><p>Now, we just need to make a variable that will be used to name all the new branches. I thought that name of the event that triggers the build will be just perfect. We can trigger the workflow for each tag with a specific prefix and use its name to create our branch.</p><p>Firstly, add the trigger:</p><pre># Trigger on every tag creation<br>on:  <br>  push:    <br>    tags:      <br>      - &#39;release-*&#39;</pre><p>Now, let&#39;s access the tag name during the workflow.</p><pre>- name: Access tag name of current workflow        <br>  run: echo &quot;TAG=${GITHUB_REF/refs\/tags\//}&quot; &gt;&gt; $GITHUB_ENV</pre><p>👆 above snippet will write the tag name into env variable called TAG</p><h3>Putting all together</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b90cdc6f47e39690a4d03eb072a07ab/href">https://medium.com/media/1b90cdc6f47e39690a4d03eb072a07ab/href</a></iframe><p>This workflow will build a swift package and push the artifacts to a separate repo, using the tag name as a new branch name. To make an alpha build, you can modify this workflow, change the tag name or trigger it on each successful merch to develop. There are a lot of options and useful actions with GitHub actions.</p><p>Happy coding! 💻</p><p>Big thanks to John(<a href="https://twitter.com/joreilly">twitter</a>) for reviewing this 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f1d4d03c962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Display Map Snapshot using Jetpack Compose]]></title>
            <link>https://proandroiddev.com/display-map-snapshot-using-jetpack-compose-e3222186a1a5?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3222186a1a5</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[google-map-api]]></category>
            <category><![CDATA[maps]]></category>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Thu, 26 Aug 2021 11:44:12 GMT</pubDate>
            <atom:updated>2021-08-30T16:58:53.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KeNHgnqEBKTM-9uJ" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jetpack Compose is gaining popularity and I personally think it is the future of Android or even multiplatform development. The library is now stable (version 1.0.1 now), however, there are still some of the view components that are not fully compatible with Compose. For those views, we can use @Composable AndroidView component and manage the updates in a composable. This blog post will share how I made an Image with a google map snapshot that updates properly when the state changes.</p><h3>Google Maps snapshot</h3><p>The Google maps API provide a <a href="https://developers.google.com/maps/documentation/android-sdk/reference/com/google/android/libraries/maps/GoogleMap.SnapshotReadyCallback#public-method-summary">callback</a> to prepare the snapshot bitmap from the currently visible map. To apply this, we need a view with Google Maps. To make it work with the Compose, we need to initialize the map in AndroidView. You can check how to use Map in Compose, investigating Crane app code from official <a href="https://github.com/android/compose-samples">google samples</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56e8ed470de62259df2f1cc122144785/href">https://medium.com/media/56e8ed470de62259df2f1cc122144785/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*hBy73_g_yHQZ4FdD_KIkeg.png" /><figcaption>Interactive map inside Composable AndroidView</figcaption></figure><p>The above code will display an interactive map with a screen width and height of 200dp. Now we need to take a snapshot and put it into Image. GoogleMap has a public snapshot lambda function that returns android.graphics.Bitmap. It uses SnapshotReadyCallback.</p><p>Since we are modifying the googleMap object in the update callback of @Composable AndroidView() , we cannot create an Image there(Composable invocations can only happen from the context of a Composable function). Therefore Image will be put in parent composable function, Box. In this scenario, the bitmap will be assigned to the function field as follows:</p><pre>val mapBitmap: MutableState&lt;Bitmap?&gt; = remember { mutableStateOf(null) }</pre><p>The @Composable Image cannot take bitmap as a parameter, but ImageBitmap. Luckily there is a converter function in compose graphics package.</p><pre><em>Image</em>(<br>    bitmap = mapBitmap.value.<em>asImageBitmap</em>(),<br>    contentDescription = &quot;Map snapshot&quot;<strong><br></strong>)</pre><p>Connecting all the blocks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/66c8ea4d6cd4d5fe8c437bead9d3172d/href">https://medium.com/media/66c8ea4d6cd4d5fe8c437bead9d3172d/href</a></iframe><p>This code works nicely most of the time, but few things may cause some trouble. Firstly, the map sometimes is not rendered yet to take a snapshot. This really surprised me, cause we are configuring our map view in coroutine scope, calling moveCamera, addMarker and snapshot {} and yet map can be displayed blank:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*I4cSxGpu4HkSqG0YJ92Oug.png" /></figure><p>This occurs because only awaitMap is suspend function. The rest of our config is simple java void methods, so we cannot be sure that the map is already positioned and rendered. We can fix that, adding another callback to the block, which is onMapLoaded. Putting the snapshot lambda inside this callback will result in a proper map view rendered into our snapshot image.</p><pre>googleMap.setOnMapLoadedCallback <strong>{<br>    </strong>googleMap.snapshot <strong>{<br>        </strong>mapBitmap.value = <strong>it</strong><br>    <strong>}<br>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*qgKoLJ_LhbMqMyfiZj6h1w.png" /><figcaption>Composable AndroidView presenting map</figcaption></figure><p>The second thing I encountered is the snapshot refreshing. Since the bitmap is held in remember{} , the AndroidView, even if it would be updated will not change the Image. We need to trigger the update on variables change. To handle such side effects, the compose API provides a few functions for extra effects. Here is the <a href="https://developer.android.com/jetpack/compose/side-effects">official doc</a>.</p><p>Since the map needs a cleanup, the best choice here would be DisposableEffect. This effect runs every time a key parameter changes or if the DisposableEffect leaves the composition.</p><pre>DisposableEffect(location) {<br>    mapBitmap.value = null<br>    onDispose <strong>{ </strong>mapBitmap.value = null <strong>}<br></strong>}</pre><p>Now, whenever the location changes, the mapBitmap is set to null and the Composable function recompose with new values. The AndroidView with map renders a new map and provides a new bitmap for Image.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70974928f5d1b80b091d29052c6df25f/href">https://medium.com/media/70974928f5d1b80b091d29052c6df25f/href</a></iframe><h3>Conclusion</h3><p>In my opinion, the current support for views like Google Map is not ideal, but it works. The need for hacking is low. My only concern is that every time we create a bitmap we have to display the map. It would be great if we could prepare this image on the background thread and display the bitmap when it’s ready. If you know how to do that, write me on <a href="https://twitter.com/piotr_prus">Twitter</a> or in response to this post. I will be happy to chat and learn.</p><p>Thanks, <a href="https://medium.com/u/3723c77a132f">Damian Petla</a> for the early review. 😉</p><p>Happy composing 💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3222186a1a5" width="1" height="1" alt=""><hr><p><a href="https://proandroiddev.com/display-map-snapshot-using-jetpack-compose-e3222186a1a5">Display Map Snapshot using Jetpack Compose</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[Custom slider in Jetpack Compose]]></title>
            <link>https://piotrprus.medium.com/custom-slider-in-jetpack-compose-43ed08e2c338?source=rss-27f05ec13608------2</link>
            <guid isPermaLink="false">https://medium.com/p/43ed08e2c338</guid>
            <dc:creator><![CDATA[Piotr Prus]]></dc:creator>
            <pubDate>Sat, 10 Jul 2021 05:14:13 GMT</pubDate>
            <atom:updated>2021-07-10T13:42:00.624Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*fCgRrsKUEHB_tzcc" /><figcaption>Photo by <a href="https://unsplash.com/@adigold1?utm_source=medium&amp;utm_medium=referral">Adi Goldstein</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jetpack compose offers a lot of ready-to-use material design <a href="https://material.io/components">components</a> to speed up and simplify UI development. However, available composables cover the basic usage, these do not perfectly reflect the components that can be seen in the material guidelines. This article will explain how to customize the Slider component from Compose API to mimic the Weather Card Example from Material Guidelines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*MtzTHASTjFjYSL9rioVcNw.gif" /><figcaption>Weather card from material.io website</figcaption></figure><h3>Foreword</h3><p>In order to get as much out of this article as possible, some basic knowledge of Jetpack Compose is required. If you have not been familiar with Jetpack Compose yet or your knowledge about it is small, I recommend this set of courses, called <a href="https://developer.android.com/courses/pathways/compose?hl=th">Compose pathway</a>.</p><p><strong><em>Disclaimer</em></strong>, The Jetpack Compose library at the time of writing this article(June 2021) is in the beta stage. API should not change, but some small changes in functionality may occur. Keep that in mind.</p><h3>Compose the Card</h3><p>I will not go into details of how to position all the elements in the card, but the below graph shows the position of Composable components names.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*C0mH5z3_8tZk4NIfIOKQ3w.png" /></figure><p>If you would like to check the exact implementation, here is the <a href="https://github.com/PiotrPrus/ComposeWeatherCard">GIT repo</a> with a fully working example. The final result, without a slider:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0YMQdSyhaPdRj2eMgRMqYg.png" /></figure><h3>The Slider</h3><p>The Composable form of slider looks a bit different from what you have seen at material.io.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SUuwsJSWHSQw8gUEpDHZ2Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*47EXkB8jjiTHOIskhsotSQ.png" /></figure><p>As you can see, this slider has dots at each discrete step, instead of lines and at every second step, there is a label. Let‘s take a look at the slider implementation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62149f5573351dc5eb7071a11b797b6f/href">https://medium.com/media/62149f5573351dc5eb7071a11b797b6f/href</a></iframe><p>What can we customize here? Value range, size via modifier, colors, number of steps. That is pretty good, but there are no parameters to customize labels or ticks(graphic equivalent are points for each step). We need to build our own Composable component that will change the shape of the tick and add labels.</p><h3>Vertical ticks</h3><p>If you check how the circle ticks are being created for Slider, you will find this code (Slider -&gt; SliderImpl -&gt; Track -&gt; Canvas):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53af19f1b4e7bfc81330e1d6d17a2f39/href">https://medium.com/media/53af19f1b4e7bfc81330e1d6d17a2f39/href</a></iframe><p>As we can see, those points are drawn on canvas, lets use the same approach for vertical ticks. First, a quick reminder of how to draw on the android canvas. Values on the x-axis (horizontal) increase in the right direction and values on the y-axis (vertical) increase from top to bottom of the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9GGqQq7fmMdkuf0oCfKWQ.png" /><figcaption>Illustration showing vertical lines in relation to the android coordinate system</figcaption></figure><p>The above illustration shows how these ticks should be drawn. These will have the constant distance and start/end padding, marked in blue. You may ask why we are not starting from (0,0). Starting from point 0 on the X axis, we won’t be able to correctly draw the thickness of the first line, because the coordinate describing the lines refers to its center, not the beginning, so starting to draw at point (0,0) we would draw a half-line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47a768fc3f4fcb9b41a95df42dc3fda6/href">https://medium.com/media/47a768fc3f4fcb9b41a95df42dc3fda6/href</a></iframe><p>Now, we can connect this function with the slider. For this I will use the box component with the option of aligning the components to center.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c5084734fd9fdbc0f03e97e976bac69/href">https://medium.com/media/8c5084734fd9fdbc0f03e97e976bac69/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zsWXklBR7Z2QKowPksvYaA.png" /><figcaption>Result of above code (ForecastSlider)</figcaption></figure><h3>Hide the original points(ticks)</h3><p>The vertical lines looks good. These are positioned in right place, center vertically, with good thickness. Now, we need to get rid of original slider points. In @Composable Slider function, there is parameter named colors of type SliderColors. To override this, we need to create @Composable function that extends SliderColors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0acec463caa6a2fec29f432222738bcb/href">https://medium.com/media/0acec463caa6a2fec29f432222738bcb/href</a></iframe><p>Using Color.Transparent as a tickColors, the points will disappear. The result with changed colors of thumb and track looks as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Iadz7kljReU2KIcASe2wQ.png" /></figure><h3>Labels</h3><p>The last missing item in our card design are labels. We could use the Row with Text functions, but manage all the spacers or padding feel very hacky to me, so I choose to continue work with a Canvas. However, there is a small issue with a @Composable Canvas. It do not provide any function for drawing text. There is a feature request for that functionality on google issue tracker. I encourage you to star it and follow -&gt; <a href="https://issuetracker.google.com/issues/190787898">Issue tracker</a>.</p><p>For now, we can use drawText function from android.graphics.Canvas, which can be easily accessed from our @Composable Canvas.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89ff4dd40a5751c10c2214cb4abfb810/href">https://medium.com/media/89ff4dd40a5751c10c2214cb4abfb810/href</a></iframe><p>As you can see on the above snippet, the text is drawn for every second tick and it is positioned at the bottom of the canvas.</p><p>Composing all of this together results in this view:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K05DqhEMY8rvaTZJ0bg4YA.png" /></figure><h3>React on slider change</h3><p>The UI part is done, but it is not over yet. We need to update the base of the measurement on the slider position.</p><p>To make things a bit more readable, let’s divide our card into two separate @Composable functions. First, called MeasurementView that will represent all of the components, without the slider and it will receive the parameter of WeatherItem class that holds all the results for one hour.</p><p>The second function will be a ForecastSlider that will take as parameters: list of dates, value(position of thumb), and caller function: onValueChange.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8276447b771d2f513377bdef699bc06/href">https://medium.com/media/b8276447b771d2f513377bdef699bc06/href</a></iframe><p>Let’s go over step by step what functions were used to connect the two views:</p><ul><li>mySelection is a mutable field that uses rememberSaveable, so the @Composable will remember about its state even on configuration changes</li><li>item is an immutable field that also uses remember, but in lambda, there is another function called, derivedStateOf. This means, that whenever one of the parameters (mySelection, list) will change, the item will be recalculated. More about it <a href="https://developer.android.com/jetpack/compose/side-effects#derivedstateof">here</a>.</li></ul><h3>The final result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*sal-1DWcbvdxoNwPXnvhyg.gif" /></figure><p>Thanks for reading this post. The full code can be found <a href="https://github.com/PiotrPrus/ComposeWeatherCard">HERE</a>.</p><p>Thanks to <a href="https://medium.com/u/3723c77a132f">Damian Petla</a> for the review and tips.</p><p>Happy coding everyone 💻 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43ed08e2c338" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>