<?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 Alex Frank on Medium]]></title>
        <description><![CDATA[Stories by Alex Frank on Medium]]></description>
        <link>https://medium.com/@alex.frank84?source=rss-5dea149161f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*C9XNFj96SNXDQGFX</url>
            <title>Stories by Alex Frank on Medium</title>
            <link>https://medium.com/@alex.frank84?source=rss-5dea149161f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 10:06:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@alex.frank84/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[Parameter Injection for Android ViewModels]]></title>
            <link>https://medium.com/better-programming/parameter-injection-for-android-viewmodels-b9e9e3448051?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e9e3448051</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 16:34:13 GMT</pubDate>
            <atom:updated>2022-09-01T15:38:53.188Z</atom:updated>
            <content:encoded><![CDATA[<h4>Handling parameter injecting in Android ViewModels using SaveStateHandler and Hilt</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LkMe52b3_HNhbGx3" /><figcaption>Photo by <a href="https://unsplash.com/es/@joshuaryanphoto?utm_source=medium&amp;utm_medium=referral">Joshua Reddekopp</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Injecting dependencies into our ViewModel is already good practice. It keeps the implementation flexible and easy to test.</p><p>But what about parameters provided to the screen or Fragment? For example, Fragment Args or Compose navigation parameters. Often something like an init method is used to receive the parameters from the View and set up the ViewModel. This adds extra steps to our ViewModel we need to be aware of. Therefore it would be more favourable to get the dependencies and the parameters in the constructor.</p><h3>Setup</h3><p>For this example, let’s keep it simple and focus mainly on handling the parameter.</p><p>We create an app with two screens:</p><ol><li>Screen 1 is just a button. Tapping it gets a random number and navigates to Screen 2, handing the random number over as a parameter.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/0*ADzQ2dTTGM6shbbV.png" /></figure><ol><li>Screen 2 receives the random number, creates a View state, and simply displays the result as a text.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*WoTG5NRuUXg-095s.png" /></figure><p>The screens are created with Jetpack Compose, and the example also uses Composes NavHost to navigate, but the same ViewModel code applies to Activities and Fragments. The only difference is the types allowed to be used as parameters. In the following setup, Compose Navigation only allows us to pass parameters as part of the navigation route String.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c514197617871ade026b1f9f479ef1a3/href">https://medium.com/media/c514197617871ade026b1f9f479ef1a3/href</a></iframe><p>As we can see, our second screen has the route details/{randomNumber} declaring the parameter randomNumber.</p><h3>Handle a Saved State</h3><p>Now to the important question. How can we retrieve the parameter in our ViewModel on the second screen after navigation?</p><p>The SavedStateHandle class contains the information we need, and it is directly injectable into the constructor of a ViewModel.</p><pre>class DetailsFlowViewModel(<br>    savedStateHandle: SavedStateHandle<br>) : ViewModel() {<br>    ...<br>}</pre><p>This is possible with or without the help of a dependency injection framework like Hilt.</p><p>SavedStateHandle provides us with two methods to get to our parameter.</p><pre>operator fun &lt;T&gt; get(key: String): T?</pre><pre>fun &lt;T&gt; getStateFlow(key: String, initialValue: T): StateFlow&lt;T&gt;</pre><p>Depending on what we want to achieve, we can use either method. In our case, we want to offer a View state flow from our ViewModel to the UI. Therefore, let’s use getStateFlow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/738efabace36fa80306033311f074dc3/href">https://medium.com/media/738efabace36fa80306033311f074dc3/href</a></iframe><blockquote><em>Important: Since we are using Compose Navigation we first have to retrieve the parameter as a String before we can convert it to its actual type Int. With Fragment Args it would be possible to directly get the parameter as an Int.</em></blockquote><h3>One Step Further</h3><p>We can already provide our parameter directly to the ViewModels constructor. But there is still a drawback: The ViewModel constructor does not tell us exactly what it wants, but, e.g., in tests, we need to know to set randomNumber of type String to the SavedStateHandle before passing it to the constructor. Sounds like it requires a lot of knowledge of implementation details.</p><p>Wouldn’t it be better if the constructor just tells us: I want to have the parameter, randomNumber, of type Int.</p><p>We can achieve this with the help of dependency injection frameworks like Hilt.</p><blockquote><em>To keep it short, I’m not going in to details on the basic usage of Hilt in this post. In case you want to read up on Hilt you can go to its </em><a href="https://developer.android.com/training/dependency-injection/hilt-android"><em>Android Developers tutorial</em></a><em>.</em></blockquote><p>First, we create a Qualifier annotation, allowing us to identify our parameter to Hilt.</p><pre>@Qualifier<br>@Retention(AnnotationRetention.BINARY)<br>annotation class RandomNumber</pre><p>With the Qualifier RandomNumber we can create a small Hilt module, providing our parameter in a ViewModel scope.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/209184e6868888e58029ad9551974949/href">https://medium.com/media/209184e6868888e58029ad9551974949/href</a></iframe><p>We install the module in ViewModelComponent, making the parameter available for the lifetime of the ViewModel it is injected in. The actual provideRandomNumber method is the code we had in the ViewModel earlier, with one difference. We don’t use a Flow but get the value directly.</p><p>With the module, our ViewModel becomes simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c51daddaee56544da29e9da0a81d6533/href">https://medium.com/media/c51daddaee56544da29e9da0a81d6533/href</a></iframe><p>We ask for the parameter we want, using the Qualifier, and simply use it to create our View state.</p><h3>Conclusion</h3><p>Using parameter injection, as shown in this post, does require a little more code than injecting a SavedStateHandle or creating an init method, but it better separates the different aspects of our app, allowing for a more readable and testable code.</p><p>The whole example with different variants using the SavedStateHandle, Hilt, and an Activity can be found on <a href="https://github.com/a-frank/viewmodel-parameters">GitHub</a>.</p><p>If you are wondering, the same concept can be achieved using Koin.</p><p>See you in the next one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e9e3448051" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/parameter-injection-for-android-viewmodels-b9e9e3448051">Parameter Injection for Android ViewModels</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parallax Scrolling using LazyColumn]]></title>
            <link>https://blog.devgenius.io/parallax-scrolling-using-lazycolumn-8df1d416888d?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8df1d416888d</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[how-to]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[parallax-scrolling]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Mon, 15 Aug 2022 11:53:45 GMT</pubDate>
            <atom:updated>2022-08-15T21:26:44.024Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TopIQYVirYKr4ttN" /><figcaption>Photo by <a href="https://unsplash.com/es/@jeremythomasphoto?utm_source=medium&amp;utm_medium=referral">Jeremy Thomas</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A parallax scrolling effect is always nice to look at and it catches the attention of the user. Using Jetpack Compose this effect can be implemented fairly easy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*Dz1pPEOFyopy8EVm.gif" /></figure><h3>Just another item</h3><p>In the example we have an image on top of a list with text items. This could mean we have an Image followed by a <strong>LazyColumn</strong>, but when looking at the API <strong>LazyColumn</strong> we can not only call the <strong>items</strong> method and give it a list with data to create our items from.</p><pre>val list = (0..1_000).map{ &quot;Item $it&quot; }.toList()</pre><pre>LazyColumn {<br>    items(list) { item -&gt;<br>        Text(text = item)<br>    }<br>}</pre><p>We can also call multiple <strong>item</strong> and <strong>items</strong> methods in the scope of a <strong>LazyColumn</strong>. It is not limited to just having it call the <strong>items</strong> function.<br>For this means, we can use <strong>item</strong> to display the image, followed by <strong>items</strong> to create the list.</p><pre>val list = (0..1_000).map{ &quot;Item $it&quot; }.toList()</pre><pre>LazyColumn {</pre><pre>    item {<br>        Image(<br>            painter = resourcePainter(id = R.drawable.image),<br>            contentDescription = &quot;Top image&quot;),<br>            contentScale = ContentScale.Crop,<br>            modifier = Modifier.fillParentMaxWidth()<br>    }</pre><pre>    items(list) { item -&gt;<br>        Text(text = item)<br>    }<br>}</pre><p>With that we already have a list with two types of items and of course right now they are scrolling in the same speed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*0AgeIIk-MbztngTe.gif" /></figure><h3>Not so fast</h3><p>In order to achieve a parallax effect, we need to reduce the scrolling speed of the image, while keeping the scrolling speed of the other items untouched.</p><p>To influence the scrolling we need</p><ol><li>A way to get to scrolling information</li><li>A way to manipulate the scrolling behaviour of the image.</li></ol><p>For the scrolling information we can utilise <strong>LazyColumns</strong> parameter <strong>LazyListState</strong>, it contains the information we need. To get to it, instead of keeping the default, we create our own and pass it in.</p><pre>val lazyListState = rememberLazyListState()</pre><pre>LazyColumn(state = lazyListState){<br>    ...<br>}</pre><p>Derived from the <strong>LazyListState</strong> we can calculate a slower translation of our image along the y-axis, compared to the other items.</p><pre>val firstItemTranslationY by remember {<br>        derivedStateOf {<br>            when {<br>                lazyListState.layoutInfo.visibleItemsInfo.isNotEmpty() &amp;&amp; lazyListState.firstVisibleItemIndex == 0 -&gt; lazyListState.firstVisibleItemScrollOffset * .6f<br>                else                                                                                               -&gt; 0f<br>            }<br>        }<br>    }</pre><p>We check if the image is visible on screen, if not we don’t want to do anything and just say behave normally, by returning a translation of 0. As long as the image is visible we take the current scrolling offset and multiple it by a number between 1 and 0. The closer the number is to 1 the slow the image will move with the scrolling. For the parallax scroll effect we want to keep the image longer in the screen as it normally would be.</p><p>You can play around with that value to adjust the speed as you like. For this example let’s keep it somewhere in the middle with 0.6.</p><p>Now we have the value to adjust our images scrolling. But where should be apply it? For that Compose offers a pretty handy <strong>Modifier</strong> that we can use. <strong>Modifier.graphicsLayer</strong> provides us with the possibility to manipulate scale, rotation, alpha, translation and more of a Composable it is applied used on.</p><p>The translation sounds like a good option. Let’s apply <strong>Modifier.graphicsLayer</strong> to our image and set the vertical translation to the value we just calculated.</p><pre>...<br>item {<br>    Image(<br>        painter = painterResource(id = R.drawable.image),<br>        contentDescription = &quot;Top image&quot;,<br>        contentScale = ContentScale.Crop,<br>        modifier = Modifier<br>            .fillParentMaxWidth()<br>            .graphicsLayer {<br>                translationY = firstItemTranslationY<br>            }<br>    )<br>}<br>...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*Ar8ZGst2OiKuGQqH.gif" /></figure><p>Just to play around a little more, let’s also fade out the image slowly while it is scrolling.</p><pre>val visibility by remember {<br>        derivedStateOf {<br>            when {<br>                lazyListState.layoutInfo.visibleItemsInfo.isNotEmpty() &amp;&amp; lazyListState.firstVisibleItemIndex == 0 -&gt; {<br>                    val imageSize = lazyListState.layoutInfo.visibleItemsInfo[0].size<br>                    val scrollOffset = lazyListState.firstVisibleItemScrollOffset</pre><pre>                    scrollOffset / imageSize.toFloat()<br>                }<br>                else                                                                                               -&gt; 1f<br>            }<br>        }<br>    }</pre><p>The procedure is basically the same as before, the difference is instead of taking the offset of the first item we take its size and its scroll offset and calculate the alpha value.</p><p>When we apply it we subtract our calculated visibility from 1 and the image will be fully transparent when it leaves the screen.</p><pre>.graphicsLayer {<br>    alpha = 1f - visibility<br>    translationY = firstItemTranslationY<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/0*-ibyffG_eX4IrMSU.gif" /></figure><h3>Conclusion</h3><p>With Jetpack Composes LazyColumn and <strong>Modifier.graphicsLayer</strong> it is really simple to create a parallax scrolling effect. Calculate the translation derived from the <strong>LazyListState</strong> and apply it to the <strong>Modifier</strong>.</p><p>The whole code for this can be found on <a href="https://github.com/a-frank/parallax-scrolling-compose">GitHub</a>.</p><p>I also added a fading TopBar to this example. I wanted to have the Back Arrow always visible and therefore ended up creating my own TopBar. If you have any ideas on how to make it work with the standard Compose TopBar, leave a comment or write me directly. I would like to hear about it :-).</p><p>Hope you enjoyed this small example on parallax scrolling.<br>See you in the next one 👋.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8df1d416888d" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/parallax-scrolling-using-lazycolumn-8df1d416888d">Parallax Scrolling using LazyColumn</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Draw the Labeled Range Slider]]></title>
            <link>https://blog.devgenius.io/draw-the-labeled-range-slider-3eb96e748e88?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3eb96e748e88</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[custom]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 07:02:49 GMT</pubDate>
            <atom:updated>2022-08-08T17:27:29.310Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*TLmLbwAbfBgoF9gM" /><figcaption>Photo by <a href="https://unsplash.com/@samplusplus?utm_source=medium&amp;utm_medium=referral">Sam Haddad</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In part 4 of this series let’s start putting everything we learned so far, and a little more, together and create our Labeled Range Slider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*72oxyYTNY9Uvgoh3.gif" /><figcaption>How the final result should look like</figcaption></figure><h3>Draw the UI</h3><p>To get started we first need to break down the different elements involved in our Composable and how to draw them.</p><p>As we can see on the following image we can break down the Labeled Range Slider into 5 elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*ISfjZja8dCUItV7f.png" /><figcaption>Breakdown of the individual elements</figcaption></figure><p>We have</p><ul><li>Labels above the slider bar, indicating the values available and selected. The color and font style should reflect our selected range (<em>Red</em>)</li><li>A rounded bar in the background, guiding our sliders (<em>Purple</em>)</li><li>Step markers, indicating all available values on our bar (<em>Green</em>)</li><li>An indication of our selected range on our bar itself (<em>Blue</em>)</li><li>And finally our slider handles which we want to drag across the bar to select our range (<em>Orange</em>)</li></ul><h3>Rounded background bar (Purple)</h3><p>The simplest element to start with and to setup our Composable is the gray bar in the background guiding our sliders. Before we get to drawing the bar, we first need to do some preparation like calculating the width and height.</p><p>For the width we want our bar to fill the entire width of the available space, with some padding for the sliders, but we will come to that later.<br>To get the size of our Composable we can use <strong>Modifier.onSizeChanged</strong> and store that value in a state.<br>Depending on that value we can determine the with of the rect. For the height, we keep it simple and let the caller configure it, but provide a reasonable default of 12 Dp.<br>Also we add a parameter for the bar color and the size of the rounded corners.</p><pre>@Composable<br>fun LabeledRangeSlider(<br>    modifier: Modifier = Modifier,<br>    barHeight: Dp = 12.dp,<br>    barColor: Color = Color.LightGray,<br>    barCornerRadius: Dp = 6.dp<br>) {</pre><pre>    var composableSize by remember { mutableStateOf(IntSize(0, 0)) }<br>    val height = barHeight<br>    val barWidth = remember(key1 = composableSize) { composableSize.width.toFloat() }<br>    val barXStart = 0f<br>    val barYStart = 0f</pre><pre>    Canvas(<br>        modifier = modifier<br>            .height(height)<br>            .onSizeChanged {<br>                composableSize = it<br>            }<br>    ) {<br>        drawRoundRect(<br>            color = barColor,<br>            topLeft = Offset(barXStart, barYStart),<br>            size = Size(barWidth, barHeight.toPx()),<br>            cornerRadius = CornerRadius(barCornerRadius.toPx(), barCornerRadius.toPx())<br>        )<br>    }<br>}</pre><p>We already prepared some variables, like <strong>height</strong>, <strong>barWidth</strong>, <strong>barXStart</strong> and <strong>barYStart</strong>. We will need them later to calculate a better positioning. The <strong>height</strong> we put into <strong>Modifier.height</strong> of our canvas and we use the best practice of allowing to pass a <strong>Modifier</strong>, so the width can be determined by the caller.</p><blockquote><em>Interesting to note: We made </em><strong><em>barWidth</em></strong><em> recalculation dependent on the size of the Composable. Since as long as the size of the Composable does not change we can just </em><strong><em>remember</em></strong><em> </em><strong><em>barWidth</em></strong><em>.</em></blockquote><p>The result so far looks like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*uZPrmBx3JKq_0k9G.png" /><figcaption>Background bar of the slider</figcaption></figure><p>What we also can see with this small snippet is that we already have the need for some configuration and the need to convert Dp to pixels with <strong>toPx</strong> for drawing is given.</p><p>What we can do to clean this up a little is, like we saw in <a href="https://dev.to/lex_fury/context-receivers-39p5">part 3</a>, introduce a configuration data class.</p><pre>data class SliderConfig(<br>    val barHeight: Dp = 12.dp,<br>    val barColor: Color = Color.LightGray,<br>    val barCornerRadius: Dp = 6.dp<br>) {<br>    context(Density)<br>    val barHeightPx: Float<br>        get() = barHeight.toPx()</pre><pre>    context(Density)<br>    val barCornerRadiusPx<br>        get() = barCornerRadius.toPx()<br>}</pre><p>We moved our config into <strong>SliderConfig</strong> and with that we can use Context Receivers to encapsulate the conversion to pixels directly in this class. This time we use <strong>Density</strong> as a <strong>Context</strong>, because it is implement by <strong>DrawScope</strong>, but can be used more general. Why? We will see in a bit :-).</p><h3>Slider handle (Orange)</h3><p>Next let’s add the slider handles. As we can see in the GIF above, the handle has a shadow around it and it also reacts to the touch, by increasing the shadow size.<br>Without the shadow we could just simply call <strong>drawCircle</strong> and be done. Unfortunately we can’t apply a shadow effect easily with the regular <strong>drawCircle</strong> function of a canvas. But luckily we can use <strong>drawIntoCanvas</strong> and its <strong>drawCircle</strong> function. It allows us to provide a <strong>Paint</strong> parameter, with which we can implement our shadow.</p><pre>private fun DrawScope.drawCircleWithShadow(<br>    position: Offset,<br>    touched: Boolean,<br>    sliderConfig: SliderConfig<br>) {<br>    val touchAddition = if (touched) {<br>        sliderConfig.touchCircleShadowTouchedSizeAdditionPx<br>    } else {<br>        0f<br>    }</pre><pre>    drawIntoCanvas {<br>        val paint = androidx.compose.ui.graphics.Paint()<br>        val frameworkPaint = paint.asFrameworkPaint()<br>        frameworkPaint.color = sliderConfig.touchCircleColor.toArgb()<br>        frameworkPaint.setShadowLayer(<br>            sliderConfig.touchCircleShadowSizePx + touchAddition,<br>            0f,<br>            0f,<br>            Color.DarkGray.toArgb()<br>        )<br>        it.drawCircle(<br>            position,<br>            sliderConfig.touchCircleRadiusPx,<br>            paint<br>        )<br>    }<br>}</pre><p>As we can see, we create a <strong>Paint</strong> object and convert it to <strong>NativePaint</strong>. This gives us access to <strong>setShadowLayer</strong>. We give the shadow a size, depending on it the circle is touched or not and draw our circle with it.<br>We also added a little bit more configuration into our <strong>SliderConfig</strong> class.</p><p>With the circle function ready we need to update the calculation of our bar. When the handle is add the end of the bar we don’t want it to overlap our Composable or worse go off-screen. Therefore we need to add a little padding to our bar.</p><p>For that we now need to access pixel values of our configuration and as we saw above for that we need to be within the <strong>Scope</strong> of <strong>Density</strong> object. One way to solve this would be to move the calculation into the <strong>onDraw</strong> lambda of our canvas. This would mean recalculate these values every time we do a draw, but they only need to be updated if either the <strong>Density</strong> or the size of our Composable changes.<br>What we can do is create a small extension function on the size and the <strong>Density</strong>.</p><pre>@Composable<br>private fun &lt;T&gt; Pair&lt;IntSize, Density&gt;.derive(additionalKey: Any? = null, block: Density.() -&gt; T): T =<br>    remember(key1 = first, key2 = additionalKey) {<br>        second.block()<br>    }</pre><p>And with that we can write our size calculations like this:</p><pre>val currentDensity = LocalDensity.current<br>val sizeAndDensity = composableSize to currentDensity</pre><pre>val barYCenter = sizeAndDensity.derive { (height / 2).toPx() }<br>val barXStart = sizeAndDensity.derive { sliderConfig.touchCircleRadiusPx }<br>val barYStart = sizeAndDensity.derive { barYCenter - sliderConfig.barHeightPx / 2f }<br>val barWidth = sizeAndDensity.derive { composableSize.width - 2 * barXStart }</pre><p>The important piece here is that we always can get the current <strong>Density</strong> with <strong>LocalDensity.current</strong> within a Composable.</p><p>Let’s position our handles at the start and end of the bar for now and draw them.</p><pre>val leftCirclePosition = remember(key1 = composableSize) {<br>    Offset(barXStart, barYCenter)<br>}<br>val rightCirclePosition = remember(key1 = composableSize) {<br>    Offset(barXStart + barWidth, barYCenter)<br>}</pre><pre>...<br>// in our Canvas<br>        drawCircleWithShadow(<br>            leftCirclePosition,<br>            false,<br>            sliderConfig<br>        )</pre><pre>        drawCircleWithShadow(<br>            rightCirclePosition,<br>            false,<br>            sliderConfig<br>        )</pre><p>The result up until now looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*6xgCM0SFx_grDOgt.png" /><figcaption>Background bar and touch handles</figcaption></figure><h3>Labels and step markers (Red and Green)</h3><p>Next we want to draw the labels above the bar as well as the step markers. It makes sense to look at them together, because a label and its step marker should be aligned correctly. What we already know is positioning on the y-axis for our labels and the step markers. The labels should be at the top of our Composable and the step markers aligned with the middle of our bar. What we still need is the positioning on the x-axis for the single steps. For that we first of allow to pass steps into our Composable and create a small function to calculate the x coordinates.</p><pre>private fun calculateStepCoordinatesAndSpacing(<br>    numberOfSteps: Int,<br>    barXStart: Float,<br>    barWidth: Float,<br>    stepMarkerRadius: Float,<br>): Pair&lt;FloatArray, Float&gt; {<br>    val stepOffset = barXStart + stepMarkerRadius<br>    val stepSpacing = (barWidth - 2 * stepMarkerRadius) / (numberOfSteps - 1)</pre><pre>    val stepXCoordinates = generateSequence(stepOffset) { it + stepSpacing }<br>        .take(numberOfSteps)<br>        .toList()</pre><pre>    return stepXCoordinates.toFloatArray() to stepSpacing<br>}</pre><p>We calculate the start to be aligned with the start of our bar and depending on the amount of steps we have, we calculate the spacing between them.</p><p>Since this calculation is not only dependent on Composable size and <strong>Density</strong>, but also on the amount of steps, we use our <strong>derive</strong> function to perform it.</p><pre>val (stepXCoordinates, stepSpacing) = sizeAndDensity.derive(steps) {<br>        calculateStepCoordinatesAndSpacing(<br>            numberOfSteps = steps.size,<br>            barXStart = barXStart,<br>            barWidth = barWidth,<br>            stepMarkerRadius = sliderConfig.stepMarkerRadiusPx<br>        )<br>    }</pre><p>Additionally we provide the steps as a second key to the <strong>remember</strong> function. This way we can ensure if the steps are changing we can update our Composable.</p><p>After we calculated the positions we can draw our labels and step markers.</p><pre>private fun &lt;T&gt; DrawScope.drawStepMarkersAndLabels(<br>    steps: List&lt;T&gt;,<br>    stepXCoordinates: FloatArray,<br>    leftCirclePosition: Offset,<br>    rightCirclePosition: Offset,<br>    barYCenter: Float,<br>    sliderConfig: SliderConfig<br>) {<br>    assert(steps.size == stepXCoordinates.size) { &quot;Step value size and step coordinate size do not match. Value size: ${steps.size}, Coordinate size: ${stepXCoordinates.size}&quot; }</pre><pre>    steps.forEachIndexed { index, step -&gt;<br>        val stepMarkerCenter = Offset(stepXCoordinates[index], barYCenter)</pre><pre>        val isCurrentlySelectedByLeftCircle =<br>            (leftCirclePosition.x &gt; (stepMarkerCenter.x - sliderConfig.stepMarkerRadiusPx / 2)) &amp;&amp;<br>                    (leftCirclePosition.x &lt; (stepMarkerCenter.x + sliderConfig.stepMarkerRadiusPx / 2))<br>        val isCurrentlySelectedByRightCircle =<br>            (rightCirclePosition.x &gt; (stepMarkerCenter.x - sliderConfig.stepMarkerRadiusPx / 2)) &amp;&amp;<br>                    (rightCirclePosition.x &lt; (stepMarkerCenter.x + sliderConfig.stepMarkerRadiusPx / 2))</pre><pre>        val paint = when {<br>            isCurrentlySelectedByLeftCircle || isCurrentlySelectedByRightCircle                     -&gt; sliderConfig.textSelectedPaint<br>            stepMarkerCenter.x &lt; leftCirclePosition.x || stepMarkerCenter.x &gt; rightCirclePosition.x -&gt; sliderConfig.textOutOfRangePaint<br>            else                                                                                    -&gt; sliderConfig.textInRangePaint<br>        }</pre><pre>        drawCircle(<br>            color = sliderConfig.stepMarkerColor,<br>            radius = sliderConfig.stepMarkerRadiusPx,<br>            alpha = .1f,<br>            center = stepMarkerCenter<br>        )</pre><pre>        drawIntoCanvas {<br>            val stepText = step.toString().let { text -&gt;<br>                if (text.length &gt; 3) {<br>                    text.substring(0, 2)<br>                } else {<br>                    text<br>                }<br>            }<br>            it.nativeCanvas.drawText(<br>                stepText,<br>                stepMarkerCenter.x - (stepText.length * sliderConfig.textSizePx) / 3,<br>                sliderConfig.textSizePx,<br>                paint<br>            )<br>        }<br>    }<br>}</pre><p>We pass in the calculated x-axis positions and the steps to iterate over them and position the step marker and the label accordingly. As you can see in the <strong>drawIntoCanvas</strong> function we are accessing the native canvas to draw our label, since the normally canvas does not have a function for drawing text.<br>Depending on the position of the two handles, we select a different paint, so that labels reflect the selected range in our slider as well.</p><p>We added more properties to our <strong>SliderConfig</strong> to control the colors, the text size, the text offset and the color of the step markers. With the additional sizes we can update the height calculation of our Composable.</p><pre>val height = remember(key1 = sliderConfig) { sliderConfig.touchCircleRadius * 2 + sliderConfig.textSize.value.dp + sliderConfig.textOffset }</pre><p>As well as the calculation of our positioning variables.</p><pre>val barYCenter = sizeAndDensity.derive { composableSize.height - sliderConfig.touchCircleRadiusPx }<br>val barXStart = sizeAndDensity.derive { sliderConfig.touchCircleRadiusPx - sliderConfig.stepMarkerRadiusPx }<br>val barYStart = sizeAndDensity.derive { barYCenter - sliderConfig.barHeightPx / 2 }<br>val barWidth = sizeAndDensity.derive { composableSize.width - 2 * barXStart }<br>val barCornerRadius = sizeAndDensity.derive { CornerRadius(sliderConfig.barCornerRadiusPx, sliderConfig.barCornerRadiusPx) }</pre><p>We put the <strong>drawStepMarkersAndLabels</strong> in our canvas below the <strong>drawRoundRect</strong>, but above the functions to draw our markers. The result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*Y6nIRwgWL7mPFrDW.png" /><figcaption>Step marker and labels are added</figcaption></figure><h3>Finalizing the UI (Blue)</h3><p>As we can see we are almost done with drawing the UI. What’s still missing is the indication of the selected range on the bar and to position our handles correctly to the currently selected value.</p><p>First we position our handles. For that we want our Composable to be able to receive these values from the caller, since we don’t want to manage this kind of state.</p><pre>@Composable<br>fun &lt;T : Number&gt; LabeledRangeSlider(<br>    selectedLowerBound: T,<br>    selectedUpperBound: T,<br>    steps: List&lt;T&gt;,<br>    modifier: Modifier = Modifier,<br>    sliderConfig: SliderConfig = SliderConfig()<br>) {<br>...<br>}</pre><p>With these two values we can update the positioning of our handles</p><pre>var leftCirclePosition by remember(key1 = composableSize) {<br>    val lowerBoundIdx = steps.indexOf(selectedLowerBound)<br>    mutableStateOf(Offset(stepXCoordinates[lowerBoundIdx], barYCenter))<br>}<br>var rightCirclePosition by remember(key1 = composableSize) {<br>    val upperBoundIdx = steps.indexOf(selectedUpperBound)<br>    mutableStateOf(Offset(stepXCoordinates[upperBoundIdx], barYCenter))<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*Zy0-pZFS_I5nMH5s.png" /><figcaption>Touch handles aligned with step markers and labels</figcaption></figure><p>Now the label of the selected step is correctly drawn with a bold font style.</p><p>The last step to complete the drawing of the UI, is to add a <strong>drawRect</strong> function below drawing the bar background with <strong>drawRoundRect</strong>.</p><pre>drawRect(<br>    color = sliderConfig.barColorInRange,<br>    topLeft = Offset(leftCirclePosition.x, barYStart),<br>    size = Size(rightCirclePosition.x - leftCirclePosition.x, sliderConfig.barHeightPx)<br>)</pre><p>To see the result better we set our <strong>selectedLowerBound</strong> and <strong>selectedUpperBound</strong> to 10 and 90 respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*ujfnUb_eXE9ds77g.png" /><figcaption>The final UI with a range indicator added</figcaption></figure><p>Looks like we finished the drawing part of our Labeled Range Slider :-).</p><h3>Make it interactive</h3><p>We are drawing everything we need for our Labeled Range Slider. Now we need to make it interactive. While writing this post I realized it is already pretty long, that’s why I decided to split up this part into another post.</p><p><a href="https://medium.com/@alex.frank84/make-the-labeled-range-slider-interactive-516bdf6e5c25">Let’s jump right into it</a> or visit <a href="https://github.com/a-frank/labeled-range-slider">GitHub</a> to explore the full source code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3eb96e748e88" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/draw-the-labeled-range-slider-3eb96e748e88">Draw the Labeled Range Slider</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make the Labeled Range Slider interactive]]></title>
            <link>https://blog.devgenius.io/make-the-labeled-range-slider-interactive-516bdf6e5c25?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/516bdf6e5c25</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[custom]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Mon, 08 Aug 2022 07:02:47 GMT</pubDate>
            <atom:updated>2022-08-08T17:27:48.213Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nrSiVrstPhEjDM1H" /><figcaption>Photo by <a href="https://unsplash.com/@eliapelle?utm_source=medium&amp;utm_medium=referral">Elia Pellegrini</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We <a href="https://medium.com/@alex.frank84/draw-the-labeled-range-slider-3eb96e748e88">created a nice looking UI</a>, yet it is pretty useless at the moment. We still have no way to interact with it. Let’s fix that.</p><p>Our touch handles should be draggable across our bar, position itself instantly when tapping on it and snap to the nearest value when the interaction is done.</p><h3>Move it</h3><p>In <a href="https://betterprogramming.pub/touch-interactions-in-jetpack-compose-caf88adcae61">part 2 of this series</a> we saw how to use gesture detectors. We could use <strong>detectTapGestures</strong> and <strong>detectDragGestures</strong> to achieve this. But since we want to do the more or less same thing when tapping or dragging, position the handle to the touch point, we can use the briefly mentioned <strong>awaitPointerEventScope</strong> to implement a more flexible and better fitting touch handler.</p><p>We can define the touch states we are interested in as a sealed class.</p><pre>sealed class TouchInteraction {<br>    object NoInteraction : TouchInteraction()<br>    object Up : TouchInteraction()<br>    data class Move(val position: Offset) : TouchInteraction()<br>}</pre><p>It is enough for us to know if there is currently no interaction, the handle should be moved to a position and that the user lifted their finger.</p><p>Our touch handler is then implemented using the <strong>pointerInput</strong> <strong>Modifier</strong>.</p><pre>fun Modifier.touchInteraction(key: Any, block: (TouchInteraction) -&gt; Unit): Modifier =<br>    pointerInput(key) {<br>        forEachGesture {<br>            awaitPointerEventScope {<br>                do {<br>                    val event: PointerEvent = awaitPointerEvent()</pre><pre>                    event.changes<br>                        .forEach { pointerInputChange: PointerInputChange -&gt;<br>                            if (pointerInputChange.positionChange() != Offset.Zero) pointerInputChange.consume()<br>                        }</pre><pre>                    block(TouchInteraction.Move(event.changes.first().position))<br>                } while (event.changes.any { it.pressed })</pre><pre>                block(TouchInteraction.Up)<br>            }<br>        }<br>    }</pre><p>We await a touch input from the user with <strong>awaitPointerEventScope</strong>, when we get one we know the user is now interacting with our Labeled Range Slider. We iterate over the events, as long as the users finger stays on our Composable, we get the absolute position of the event and we pass it on as a <strong>TouchInteraction.Move</strong> event ourselves. As soon as the user lifts their finger, we respond with <strong>TouchInteraction.Up</strong> giving our UI the chance to react by snapping the handle to the nearest step.</p><p>In our Composable we add the <strong>Modifier</strong> to the canvas, add three state variables to keep track of the current interaction state and add logic to update the position of our handles.</p><pre>var touchInteractionState by remember { mutableStateOf&lt;TouchInteraction&gt;(TouchInteraction.NoInteraction) }<br>var moveLeft by remember { mutableStateOf(false) }<br>var moveRight by remember { mutableStateOf(false) }<br>...</pre><pre>Canvas(<br>    modifier = modifier<br>        .touchInteraction(remember { MutableInteractionSource() }) {<br>            touchInteractionState = it<br>        }<br>) {<br>    ...<br>}</pre><pre>when (val touchInteraction = touchInteractionState) {<br>    is TouchInteraction.Move -&gt; {<br>        val touchPositionX = touchInteraction.position.x<br>        if (abs(touchPositionX - leftCirclePosition.x) &lt; abs(touchPositionX - rightCirclePosition.x)) {<br>            leftCirclePosition = calculateNewLeftCirclePosition(touchPositionX, leftCirclePosition, rightCirclePosition, stepSpacing, stepXCoordinates.first())<br>            moveLeft = true<br>        } else {<br>            rightCirclePosition = calculateNewRightCirclePosition(touchPositionX, leftCirclePosition, rightCirclePosition, stepSpacing, stepXCoordinates.last())<br>            moveRight = true<br>        }<br>    }<br>    is TouchInteraction.Up   -&gt; {<br>        moveLeft = false<br>        moveRight = false<br>        touchInteractionState = TouchInteraction.NoInteraction<br>    }<br>    else                     -&gt; {<br>        // nothing to do<br>    }<br>}</pre><p>We need to know which handle to move. For that we look at the x position of the touch interaction, calculate the distance between the left and the right handle and move the handle the interaction was closest to. When calculating the new position of the handle we need to take into account, that the handle should not leave the bar and that the two handles should not overlap while moving. To make it clearer let’s have a quick look at the calculation of the updated position of the left handle.</p><pre>private fun calculateNewLeftCirclePosition(<br>    touchPositionX: Float,<br>    leftCirclePosition: Offset,<br>    rightCirclePosition: Offset,<br>    stepSpacing: Float,<br>    firstStepXPosition: Float<br>): Offset = when {<br>    touchPositionX &lt; firstStepXPosition                    -&gt; leftCirclePosition.copy(x = firstStepXPosition)<br>    touchPositionX &gt; (rightCirclePosition.x - stepSpacing) -&gt; leftCirclePosition<br>    else                                                   -&gt; leftCirclePosition.copy(x = touchPositionX)<br>}</pre><p>As we can see depending on the touch position, the position of the other handle and the spacing of the steps and in this case the position of the first step, we calculate the new position the left handle is allowed to have.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Yh5llxVOnanpeYBs.gif" /><figcaption>Labeled Rang Slider still missing the snap to value feature</figcaption></figure><p>The handles move while touching the slider, we can tap on a position the handle instantly jumps to it and we even can move between the two handles without lifting the finger.</p><h3>Make it snappy</h3><p>The handles don’t behave how we want it yet. They should snap to the nearest step after the user lifts their finger, as well as when the controlled handle is changed. To make that happen we update our touch interaction logic, finding the nearest step and its x-coordinate and updating the handle position accordingly.</p><pre>is TouchInteraction.Move -&gt; {<br>    val touchPositionX = touchInteraction.position.x<br>    if (abs(touchPositionX - leftCirclePosition.x) &lt; abs(touchPositionX - rightCirclePosition.x)) {<br>        leftCirclePosition = calculateNewLeftCirclePosition(touchPositionX, leftCirclePosition, rightCirclePosition, stepSpacing, stepXCoordinates.first())<br>        moveLeft = true</pre><pre>        if (moveRight) {<br>            val (closestRightValue, _) = stepXCoordinates.getClosestNumber(rightCirclePosition.x)<br>            rightCirclePosition = rightCirclePosition.copy(x = closestRightValue)<br>            moveRight = false<br>        }<br>    } else {<br>        rightCirclePosition = calculateNewRightCirclePosition(touchPositionX, leftCirclePosition, rightCirclePosition, stepSpacing, stepXCoordinates.last())<br>        moveRight = true</pre><pre>        if (moveLeft) {<br>            val (closestRightValue, _) = stepXCoordinates.getClosestNumber(leftCirclePosition.x)<br>            leftCirclePosition = leftCirclePosition.copy(x = closestRightValue)<br>            moveLeft = false<br>        }<br>    }<br>}<br>is TouchInteraction.Up   -&gt; {<br>    val (closestLeftValue, closestLeftIndex) = stepXCoordinates.getClosestNumber(leftCirclePosition.x)<br>    val (closestRightValue, closestRightIndex) = stepXCoordinates.getClosestNumber(rightCirclePosition.x)<br>    if (moveLeft) {<br>        leftCirclePosition = leftCirclePosition.copy(x = closestLeftValue)<br>        moveLeft = false<br>    } else if (moveRight) {<br>        rightCirclePosition = rightCirclePosition.copy(x = closestRightValue)<br>        moveRight = false<br>    }<br>    touchInteractionState = TouchInteraction.NoInteraction<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*BI8YQGiQY-AtZW8g.gif" /><figcaption>The Labeled Range Slider</figcaption></figure><p>Now that already looks like the final result we want to achieve :-). But there is one minor detail missing: We still need to communicate the updated range back to our caller, so they can react on it ;-).</p><p>This final step is now pretty easy. We add a callback <strong>onRangeChanged</strong> as parameter to our Composable.</p><pre>@Composable<br>fun &lt;T : Number&gt; LabeledRangeSlider(<br>    selectedLowerBound: T,<br>    selectedUpperBound: T,<br>    steps: List&lt;T&gt;,<br>    onRangeChanged: (lower: T, upper: T) -&gt; Unit,<br>    modifier: Modifier = Modifier,<br>    sliderConfig: SliderConfig = SliderConfig()<br>)</pre><p>And simply call it every time the user lifts their finger with the value of the selected steps.</p><pre>is TouchInteraction.Up   -&gt; {<br>    val (closestLeftValue, closestLeftIndex) = stepXCoordinates.getClosestNumber(leftCirclePosition.x)<br>    val (closestRightValue, closestRightIndex) = stepXCoordinates.getClosestNumber(rightCirclePosition.x)<br>    if (moveLeft) {<br>        leftCirclePosition = leftCirclePosition.copy(x = closestLeftValue)<br>        onRangeChanged(steps[closestLeftIndex], steps[closestRightIndex])<br>        moveLeft = false<br>    } else if (moveRight) {<br>        rightCirclePosition = rightCirclePosition.copy(x = closestRightValue)<br>        onRangeChanged(steps[closestLeftIndex], steps[closestRightIndex])<br>        moveRight = false<br>    }<br>    touchInteractionState = TouchInteraction.NoInteraction<br>}</pre><h3>Conclusion</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*orgZ_qhEuVHsrmSg.gif" /><figcaption>The final Labeled Range Slider with a representation of the selected values</figcaption></figure><p>We did it 🎉. We created our own Labeled Range Slider from scratch, drawing everything our Composable needs ourselves and making it interactive with the respective <strong>Modifier</strong> 🥳.</p><p>The entire source code of the Labeled Range Slider can be found on <a href="https://github.com/a-frank/labeled-range-slider">GitHub</a>.</p><p>I hope you enjoyed following along this series and had some helpful inspiration :-).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=516bdf6e5c25" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/make-the-labeled-range-slider-interactive-516bdf6e5c25">Make the Labeled Range Slider interactive</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Receivers]]></title>
            <link>https://medium.com/@alex.frank84/context-receivers-9265b29a6ff1?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9265b29a6ff1</guid>
            <category><![CDATA[receiver]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Wed, 27 Jul 2022 09:31:05 GMT</pubDate>
            <atom:updated>2022-08-08T07:05:47.894Z</atom:updated>
            <content:encoded><![CDATA[<p>On this third part we take a look at Kotlin Context Receivers and how it can help us, before we start putting every together in <a href="https://medium.com/@alex.frank84/draw-the-labeled-range-slider-3eb96e748e88">part 4</a> and finish up our Labeled Range Slider in <a href="https://dev.to/lex_fury/make-the-labeled-range-slider-interactive-5gf">part 5</a>.</p><p>First let’s see what a Context Receiver is, before we take a look at how it can help us make our component easier to use.</p><blockquote><strong>Important:</strong> Kotlin Context Receiver is an experimental API, this means it could still be subject to change in the future, before a final release. Also the IDE support is currently limited as well.</blockquote><h3>Enabling Context Receivers</h3><p>Because of the experimental nature of Context Receivers, they are not enabled by default. To enable its usage we need to go to the <strong>build.gradle.kts</strong> or <strong>build.gradle</strong> file of our module and add <strong>-Xcontext-receivers</strong> as a free compiler arg.</p><p>In the <strong>build.gradle</strong> file of an Android module this looks something like this:</p><pre>android {<br>    ...<br>    kotlinOptions {<br>        jvmTarget = &#39;1.8&#39;<br>        freeCompilerArgs = [&quot;-Xcontext-receivers&quot;]<br>    }<br>    ...<br>}</pre><h3>How it works</h3><p>With Context Receivers we can add one or more contexts to our functions or methods. This provides the functionality of the declared context within our function, like having another <strong>this</strong> in that function. We are then able to call methods of that context as if our function is part of the object.</p><p>At a first glance this sounds a little bit like extension functions, similar to</p><pre>fun String.toast(activity: Activity, duration: Int = Toast.<em>LENGTH_LONG</em>) {<br>   Toast.makeText(activity, this, duration).show()<br>}</pre><p>What you can see in this function is, that we also need an Android Activity to call the <strong>Toast.makeText</strong> function, therefore we need to call the function like this:</p><pre>&quot;Hello Toast&quot;.<em>toast</em>(this@MainActivity)</pre><p>We know we only want to call this function from an Android Activity, since this shows an UI element. What we can do with Context Receiver, we can declare our <strong>toast</strong> function to be callable within the <strong>Scope</strong> of an Android Activity.</p><pre>context(Activity)<br>fun String.toast(duration: Int = Toast.<em>LENGTH_LONG</em>) {<br>   Toast.makeText(this@Activity, this, duration).show()<br>}</pre><p>As you can see, we removed the parameter Activity and instead added a Context Receiver, saying this function is valid within the <strong>Scope</strong> of an Activity. This allows us to call <strong>toast</strong> without passing an Activity directly, as long as we are within the <strong>Scope</strong> of one.</p><pre>&quot;Hello Toast&quot;.<em>toast</em>()</pre><p>On top of that our function now communicates to our team members, that it is only allowed to call this function in an Activity and not e.g. in a background service.</p><p>One question that comes up is, what happens when we are not within the <strong>Scope</strong> of an object needed as Context Receiver? <br>Just as an example, lets change our <strong>toast</strong> function to have an Activity and a String as Context Receivers</p><pre>context(Activity, String)<br>fun contextToast(duration: Int = Toast.<em>LENGTH_LONG</em>) {<br>   Toast.makeText(this@Activity, this@String, duration).show()<br>}</pre><p>Now we need our String also to be in <strong>Scope</strong>. We can achieve this by using Kotlin’s <strong>with</strong> function.</p><pre><em>with</em>(&quot;Hello Context&quot;) <strong>{<br>   </strong><em>contextToast</em>()<br><strong>}</strong></pre><p>Sure, this is a little bit of an odd example, but it demonstrates how we can create a <strong>Scope</strong> and also how to use multiple Context Receivers :-).</p><h3>How does this help us?</h3><p>For our Labeled Range Slider, Context Receivers can help us makes our API cleaner and simpler to use for the caller and for us.</p><p>To start simple, we want to draw a text on a canvas and give the user the ability to configure the text size, as well as the horizontal and vertical translation of the positioning. In our Composable we need pixel values to position and draw the text. But we don’t want the callers of our Composable to have to calculate pixel values by themselves and offer them an API which can be used with <strong>Dp</strong> and/or <strong>Sp</strong> values.<br>For that we create a configuration class <strong>TextConfig</strong>, holding the configurable properties and give them some defaults.</p><pre>class TextConfig(<br>   ...<br>   private val verticalTranslation: Dp = 0.<em>dp</em>,<br>   private val horizontalTranslation: Dp = 0.<em>dp</em>,<br>   private val size: TextUnit = 8.<em>sp</em>,<br>   ...<br>)</pre><p>To be able to convert <strong>Dp</strong> or <strong>Sp</strong> values into pixels, we can use <strong>toPx</strong>, as we already saw in <a href="https://dev.to/lex_fury/touch-interactions-in-jetpack-compose-5be9">part two</a> of this series. The function <strong>toPx</strong> is only available while we are within the <strong>DrawScope</strong> of a canvas. Therefore we could either call <strong>toPx</strong> manually every time in our canvas or we can use Context Receivers and create a nice computed properties, making it easier to use.</p><pre>class TextConfig(<br>   ...<br>   private val verticalTranslation: Dp = 0.<em>dp</em>,<br>   private val horizontalTranslation: Dp = 0.<em>dp</em>,<br>   private val size: TextUnit = 8.<em>sp</em>,<br>   ...<br>) {<br>   context(DrawScope)<br>   val sizePx: Float<br>      get() = size.<em>toPx</em>()<br><br>   context(DrawScope)<br>   val verticalTranslationPx: Float<br>      get() = verticalTranslation.<em>toPx</em>()<br><br>   context(DrawScope)<br>   val horizontalTranslationPx: Float<br>      get() = horizontalTranslation.<em>toPx</em>()<br><br>}</pre><p>With that we can implement our Composable as follows:</p><pre>@Composable<br>fun DrawText(<br>   textConfig: TextConfig<br>) {<br>   var enteredText by <em>remember </em>{ <em>mutableStateOf</em>(&quot;&quot;) }<br>   <em>Column</em>(<br>      modifier = Modifier.<em>padding</em>(16.<em>dp</em>)<br>   ) {<br>      <em>TextField</em>(<br>         value = enteredText,<br>         onValueChange = { enteredText = it }<br>      )<br>      <em>Canvas</em>(<br>         modifier = Modifier<br>            .<em>fillMaxSize</em>()<br>            .<em>background</em>(color = Color.DarkGray)<br>      ) {<br>         val paint = Paint().<em>apply </em>{<br>            <em>textSize </em>= textConfig.sizePx<br>         }<br>         val x = (size.width / 2f) - <br>             (enteredText.length / 4f * textConfig.sizePx) +<br>             textConfig.horizontalTranslationPx<br>         val y = size.height / 2f + <br>             textConfig.sizePx / 2f +<br>             textConfig.verticalTranslationPx<br>         <em>drawIntoCanvas </em>{<br>            it.<em>nativeCanvas</em>.drawText(<br>               enteredText,<br>               x,<br>               y,<br>               paint<br>            )<br>         }<br>      }<br>   }<br>}</pre><p>We can see, that as long as we are in the <strong>Scope</strong> of the Canvas we can call our properties, bounds to the <strong>DrawScope</strong>, because the lambda of the Canvas provides the <strong>DrawScope</strong> as an extension function parameter and there as <strong>this</strong>.</p><p>The user of the Composable can provide their configuration with device independent values.</p><pre>val config = TextConfig(<br>   size = 32.<em>sp</em>,<br>   verticalTranslation = 16.<em>dp</em>,<br>   horizontalTranslation = 32.<em>dp</em>,<br>)<br>DrawText(<br>   textConfig = config<br>)</pre><h3>Conclusion</h3><p>With the Context Receivers we can provide a nice API to our users, while also making our lives easier for the implementation of our Composable.</p><p>All the code shown here and a little bit more can be found <a href="https://github.com/a-frank/composable-and-context-receivers">on GitHub</a>.</p><p>Now that we know how to draw elements on a canvas, interactive with them using gesture detection and also are able to create a nice simple API, we got all parts ready to implement our Labeled Range Slider.</p><p><a href="https://medium.com/@alex.frank84/draw-the-labeled-range-slider-3eb96e748e88">Go to the fourth part right away</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9265b29a6ff1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Touch Interactions in Jetpack Compose]]></title>
            <link>https://medium.com/better-programming/touch-interactions-in-jetpack-compose-caf88adcae61?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/caf88adcae61</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 08:48:48 GMT</pubDate>
            <atom:updated>2022-07-12T09:02:11.618Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build a draggable Labeled Range Slider</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*er_eCInOk-whBK8o" /><figcaption>Photo by <a href="https://unsplash.com/@lishakov?utm_source=medium&amp;utm_medium=referral">Andrej Lišakov</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>After we learned how to draw different shapes on a Canvas in the <a href="https://medium.com/@alex.frank84/custom-composable-with-jetpack-compose-912d8c53b810">first part of the series</a>, let’s have a look at how to handle touch interaction in this second part.</p><p>Just as a reminder, with this topic we will be able to make our Labeled Range Slider draggable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*E7YGO2-tBefdm9C1FGYWug.gif" /></figure><p>To keep it simple we will create a Scribble Composable, to explore how we can handle touch interactions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*j3ATksAGP9Prymf9EZ39hw.png" /><figcaption>Scribble Composable</figcaption></figure><h3>Touch Interaction</h3><p>For a regular interactive Composable we would normally use either the Modifier clickable:</p><pre><em>Canvas</em>(<br>   modifier = Modifier.<em>clickable </em><strong>{<br>      </strong>Log.i(&quot;Tag&quot;, &quot;Canvas clicked&quot;)<br>   }<br>) {<br>   // draw something<br>}</pre><p>or the experimental combinedClickable:</p><pre><em>Canvas</em>(<br>   modifier = Modifier.<em>combinedClickable</em>(<br>      onClick = { Log.i(&quot;Tag&quot;, &quot;Canvas clicked&quot;) },<br>      onLongClick = { Log.i(&quot;Tag&quot;, &quot;Canvas long clicked&quot;) },<br>      onDoubleClick = { Log.i(&quot;Tag&quot;, &quot;Canvas double clicked&quot;) }<br>   )<br>) {<br>   // draw something<br>}</pre><p>Both work great if we just want to handle a click on the whole Composable.</p><p>But for our example, we want to have a little bit more control. We need to know the exact location where the click happens and also if the user drags the finger across the screen or not. Luckily Compose offers us the Modifier pointerInput<strong>, </strong>which provides the information we need.</p><h3>Gesture detectors</h3><p>The easiest way to use <strong>pointerInput</strong> is to implement one of several already provided gesture detectors.</p><ul><li>detectTapGestures: This is most similar to the combinedClickable Modifier, handling tap, double tap, press and long press. The difference this Modifier provides us with the exact position the user taped within our Composable.</li><li>detectDragGestures: With this detector we can detect the start, the end and the path a finger is dragged along in our Composable.</li><li>detectHorizontalDragGestures: As the name suggests, this is similar to detectDragGestures, but only provides us with the update for horizontal drag movements.</li><li>detectVerticalDragGestures: This is like detectHorizontalDragGestures, but only provides vertical drag movements.</li><li>detectDragGesturesAfterLongPress: Using this detector we get the same information as detectDragGestures, but only after the user performed a long press.</li><li>detectTransformGestures: The transformation gesture detector provides us with updated position information for rotating, panning and zooming gestures.</li></ul><p>If these predefined detectors are still not enough and you want full control over how a touch is handled, you can use awaitPointerEventScope.</p><p>For our example of a Scribble Composable, we will focus on using detectDragGestures<strong>.</strong> Since this detector lets us know where the user is starting the touch and also constant updates while the finger is dragged across our Composable.</p><pre><em>Canvas</em>(<br>   modifier = modifier<br>      .<em>pointerInput</em>(key1 = <em>Unit</em>) {<br>         detectDragGestures(<br>            onDragStart = { touch -&gt;<br>               Log.i(&quot;Tag&quot;, &quot;Start of the interaction is $touch&quot;)<br>            },<br>            onDrag = { change, dragAmount -&gt;<br>               Log.i(&quot;Tag&quot;, &quot;Dragged $dragAmount; Result $change&quot;)<br>            }<br>         )<br>      }<br>) {<br>   // draw something<br>}</pre><p>Here we registered a drag gesture detector within pointerInput. For the parameter key1 we simply provide Unit. Since we don’t want our detection to be canceled when key1 changes. In pointerInput we then call detectDragGestures. This gives us the information where the user starts the interaction in the callback onDragStart, as well as continuous updates of the path the finger takes in onDrag.</p><p>The onDrag callback has two parameters, the second one gives us the delta to the last drag we got. This is not the absolute position of where the finger is right now, but only the change to the last position update. The first parameter on the other hand provides us with more details, like historical data and also the absolute position of the finger on our Composable.</p><p>To keep it simple we will be using the first parameter change to get the absolute position for creating a line drawing.</p><pre>var points by <em>remember </em>{ <em>mutableStateOf</em>&lt;List&lt;Offset&gt;&gt;(<em>emptyList</em>()) }<br><br>...<br>         detectDragGestures(<br>            onDragStart = { touch -&gt;<br>               points = <em>listOf</em>(touch)<br>            },<br>            onDrag = { change, _ -&gt;<br>               val newPoint = change.position<br>               points = points + newPoint<br>            }<br>         )<br>...</pre><p>First we create a mutable state points that can hold a list of Offsets, that will hold the path the finger was dragged along on our Canvas. When the drag gesture begins we create a new list and add the touch point to it. After that we simply can look at change.position, which gives us the absolute position of the touch on our Canvas and we can add this to our path.</p><p>This way works and we can get a decent result when drawing our path right now. But if we want to have a smoother result we should consider the historical data as well.</p><pre>...<br>onDrag = <strong>{ </strong>change, _ <strong>-&gt;<br>   </strong>val pointsFromHistory = change.historical<br>      .<em>map </em><strong>{ it</strong>.position <strong>}<br>      </strong>.<em>toTypedArray</em>()<br>   val newPoints = <em>listOf</em>(*pointsFromHistory, change.position)<br>   points = points + newPoints<br><strong>}<br>...</strong></pre><p>Here we iterate over the historical data, which represents points between two <strong>onDrag </strong>updates,<strong> </strong>and get its positions. With that, we simply add the historical positions and the current position to our path list.</p><p>All that is now left to do is to draw the path on our Canvas, using the <strong>drawPath </strong>method we saw in the first part of this series.</p><pre>...<br>if (points.size &gt; 1) {<br>   val path = <em>Path</em>().<em>apply </em>{<br>      val firstPoint = points.<em>first</em>()<br>      val rest = points.subList(1, points.size - 1)<br><br>      moveTo(firstPoint.x, firstPoint.y)<br>      rest.<em>forEach </em>{<br>         lineTo(it.x, it.y)<br>      }<br>   }<br><br>   drawPath(path, color, style = Stroke(width = lineWidth.<em>toPx</em>()))<br>}<br>...</pre><p>When we have more than one point in our list we create a new Path object, move the start of the Path to our first point and then add all lines we have in our list to the Path. Since we want just lines to be draw without filling the area, we draw our path with the style Stroke.</p><p>In this implementation the tightness of the line to be drawn is parametrized as lineWidth of type Dp, but Stoke wants pixels as its width parameter. Luckily the DrawScope of our Canvas offers us with the extension function toPx, with which we can convert Dp to pixels.</p><h3>Conclusion</h3><p>We are now able to handle touch interactions on our custom Composable and translate them to actions. With that, we can draw our Labeled Range Slider and also interact with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*t8k4wC9_r4kNedaR8bTo6g.png" /></figure><p>But before we get into implementing it, we take a small excursion to the new Kotlin Context Receivers in part 3. Stay tuned.</p><p>The whole code of the Scribble Composable can be found on <a href="https://github.com/a-frank/touch-interaction-composable">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=caf88adcae61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/touch-interactions-in-jetpack-compose-caf88adcae61">Touch Interactions in Jetpack Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build Custom Composables With Jetpack Compose]]></title>
            <link>https://medium.com/better-programming/custom-composable-with-jetpack-compose-912d8c53b810?source=rss-5dea149161f------2</link>
            <guid isPermaLink="false">https://medium.com/p/912d8c53b810</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Alex Frank]]></dc:creator>
            <pubDate>Tue, 05 Jul 2022 09:05:58 GMT</pubDate>
            <atom:updated>2022-08-08T07:07:56.697Z</atom:updated>
            <content:encoded><![CDATA[<h4>Create custom views</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R9-Hf7dfxICtJtL4" /><figcaption>Photo by <a href="https://unsplash.com/@andriklangfield?utm_source=medium&amp;utm_medium=referral">Andrik Langfield</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Jetpack Compose already offers us a huge library of components to create our UI. But in order to create a more delightful and custom experience for the user, we sometimes need to create our own.</p><p>In my first article series, I want to talk about how to create custom views in Jetpack Compose.</p><p>In the example of a Labeled Ranged Slider, we go through the steps needed to create a fully custom Composable.</p><p>I chose this example because the current version of the Range Slider in Compose only offers a Float Range and no easy way to display step aligned labels, changing its appears in accordance to the selected range.</p><p>The result of this series will look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*XYR4BX02KdQqfk0lIY4Esw.gif" /><figcaption>Labeled Range Slider in motion</figcaption></figure><p>We will look at three different topics used to create the Composable and in the end we put it all together.</p><ul><li>How to draw on a Canvas (This part)</li><li><a href="https://medium.com/@alex.frank84/touch-interactions-in-jetpack-compose-caf88adcae61">Handling touch interaction</a></li><li><a href="https://medium.com/@alex.frank84/context-receivers-9265b29a6ff1">Kotlin Context Receivers</a> (because it’s new and fun :-D)</li><li><a href="https://medium.com/@alex.frank84/draw-the-labeled-range-slider-3eb96e748e88">Draw the Labeled Range Slider</a></li><li><a href="https://medium.com/@alex.frank84/make-the-labeled-range-slider-interactive-516bdf6e5c25">Interact with the Labeled Range slider</a></li></ul><p>All the code and projects will be published on <a href="https://github.com/a-frank">GitHub</a> as we go along.</p><h3>How to draw on a Canvas</h3><p>Let’s start with looking at how to draw something on a Canvas within a Composable.</p><p>As a first simple step, we draw a basic shape, like a circle. To do this we</p><ul><li>Create our Composable</li><li>Give it a minimum size</li><li>Add a Canvas</li><li>Draw the circle</li></ul><pre>@Composable<br>fun DrawSimpleCircle(<br>   color: Color,<br>   modifier: Modifier = Modifier,<br>   minSize: DpSize = <em>DpSize</em>(32.<em>dp</em>, 32.<em>dp</em>)<br>) {<br>   <em>Canvas</em>(modifier = modifier.<em>size</em>(minSize)) {<br>      drawCircle(color)<br>   }<strong><br></strong>}</pre><p>The result of this Composable will be a circle in the given color, filling the size of the whole Composable. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/71/1*iRzcYlXD89MEh6Yyc0U8HA.png" /><figcaption>A simple green circle</figcaption></figure><p>Additionally, this API allows us to draw our shapes not only with a single color, but also offers a more flexible Brush variant. With a Brush we are able to achieve gradients as well. The example shows a gradient with two colors, but the API allows for a variable list of colors if desired.</p><pre><em>...</em><strong><br></strong>drawCircle(<br>   brush = Brush.radialGradient(<br>      colors = <em>listOf</em>(<br>         centerColor, outerColor<br>      )<br>   )<br>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/54/1*PB_ZAOQMuSflOS9UFFe-nA.png" /><figcaption>A circle with radial gradient</figcaption></figure><p>A Canvas in Compose can of course not only draw circles. It offers a multitude of different drawing methods<em>.</em></p><p>Here are examples of the offers methods and a what it might look like.</p><p>drawRect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*w2VmJxEYJgys2tlw6JkMvg.png" /></figure><p>drawRoundRect:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/110/1*l_SIeHhvGuC0CMknm8DDgA.png" /></figure><p>drawLine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/109/1*eiEuQSXMxBKjLHCyscLJLg.png" /></figure><p>drawOval:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/130/1*ZOsbDfnr_hneoLktO4NU5Q.png" /></figure><p>drawArc:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/118/1*ojmfJmDLr7QcJeVx1mOoow.png" /></figure><pre>...<br>drawArc(<br>   color = color,<br>   startAngle = 180f,  // 0f is at 3 o&#39;clock of the circle<br>   sweepAngle = 180f,  // go 180° from startAngle<br>   useCenter = false,  // whether to fill the arc or not<br>   style = Stroke(width = 2.<em>dp</em>.<em>toPx</em>())<br>)</pre><p>drawPath:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*ZxuQIzF3D1ewiVs5hhUB9Q.png" /></figure><pre>...<br>val path = <em>Path</em>().<em>apply </em>{<br>   lineTo(size.width, 0f)   // line from start to end<br>   quadraticBezierTo(       // arc from the top to  bottom<br>      size.width / 2, size.height / 2,<br>      size.width, size.height<br>   )<br>   lineTo(0f, size.height)  // line from end to start<br>   quadraticBezierTo(       // arc from bottom to top <br>      size.width / 2, size.height / 2,<br>      0f, 0f<br>   )<br>   close()                   // link end to start<br>}<strong><br><br></strong>drawPath(<br>   color = color,<br>   path = path,<br>   style = Stroke(width = 2.<em>dp</em>.<em>toPx</em>())<br>)</pre><p>drawPoints:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*LLaOP7sToXRGwEb1cKMG4Q.png" /></figure><p>drawOutline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/112/1*fn7zJbk8Fs2xw7cPQa_nAQ.png" /></figure><p>drawImage:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/89/1*LiEvPV9EYFa9Gckv4b9WpA.png" /></figure><pre>...<br>drawImage(<br>   image = image,<br>   dstSize = <em>IntSize</em>(size.width.toInt(), size.width.toInt()),<br>   colorFilter = ColorFilter.lighting(Color.Yellow, Color.Red)<br>)</pre><h3>Native Canvas</h3><p>One useful draw function that is not offered directly within the Canvas Composable is the ability to draw a text. But we can still achieve this by using the drawIntoCanvas<em> </em>method. It gives us access to the native Canvas, which offers a drawText method.</p><p>Important to note: When using the native Canvas you have to resort to the android.graphics<em> </em>package, using its Paint or Color classes instead of the Compose variants.</p><pre><em>Canvas</em>(modifier = modifier.<em>size</em>(minSize)) {<br>   val paint = android.graphics.Paint()<br>   paint.<em>textSize </em>= textSize.<em>toPx</em>()<br>   paint.<em>color </em>= android.graphics.Color.<em>BLACK<br>   drawIntoCanvas </em>{<br>      it.<em>nativeCanvas</em>.drawText(text, 0f, 0f, paint)<br>   }<br>}</pre><h3>Conclusion</h3><p>With the Canvas and the native Canvas, we are able to draw everything we need for our Labeled Range Slider.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*t8k4wC9_r4kNedaR8bTo6g.png" /><figcaption>How our final result will look like</figcaption></figure><p>In the next part, we will take a look at how we can make our custom Composable interactive by reacting to touch events. <a href="https://medium.com/@alex.frank84/touch-interactions-in-jetpack-compose-caf88adcae61">Go to part 2 directly</a>.</p><p>The code for creating the images in this post can be found on <a href="https://github.com/a-frank/draw-canvas-composable">GitHub</a><strong>.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=912d8c53b810" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/custom-composable-with-jetpack-compose-912d8c53b810">Build Custom Composables With Jetpack Compose</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>