<?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 Kurt Lemond Capatan on Medium]]></title>
        <description><![CDATA[Stories by Kurt Lemond Capatan on Medium]]></description>
        <link>https://medium.com/@kurtlemond?source=rss-708c4d82f76e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-s_rBfP6vvjsg6Fz2OzleQ.jpeg</url>
            <title>Stories by Kurt Lemond Capatan on Medium</title>
            <link>https://medium.com/@kurtlemond?source=rss-708c4d82f76e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 19:12:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kurtlemond/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[Making grid items’ size identical using SubcomposeLayout in Jetpack Compose]]></title>
            <link>https://medium.com/@kurtlemond/making-grid-items-size-identical-using-subcomposelayout-in-jetpack-compose-d0249f033d16?source=rss-708c4d82f76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0249f033d16</guid>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Kurt Lemond Capatan]]></dc:creator>
            <pubDate>Fri, 10 Mar 2023 22:54:55 GMT</pubDate>
            <atom:updated>2023-03-10T22:54:55.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cpSnL8GKvawoH4puPKI-Zg.jpeg" /><figcaption>taken from <a href="https://www.pexels.com/photo/green-woven-pavement-570047/">https://www.pexels.com/photo/green-woven-pavement-570047/</a></figcaption></figure><p>While working on an android project, one of its features is a vertical grid that displays items with expiration dates. Each item’s width and height may vary depending on its content and allowed space. Take a look at the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIIlUpOw4BUmuCqhCdO8Dw.png" /><figcaption>Grid Items in different sizes. Code can be found <a href="https://gist.github.com/annoyinglemon/33b5eba08595f49cf97015cef066b0f9">here</a>.</figcaption></figure><p>From left to right:</p><ul><li>Width and height are not restricted, texts inside take as much width and height as possible</li><li>The item’s size is 150x150 dp square. The expiration goes to a new row because it exceeds the available space.</li><li>The item’s width is 120dp. This time both ‘available’ and expiration texts goes to new lines due to a narrow width.</li></ul><p>Each text row inside the item utilizes <a href="https://google.github.io/accompanist/flowlayout/">FlowRow</a>, a special row from Accompanist that allows children to go to a new line if there is insufficient space.</p><p>Now let’s put them inside a lazy vertical grid. Given the number of columns and equal span sizes, this is the result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taPN-htEO-Op3kFOu8KyaA.png" /><figcaption>The left grid has 350 dp width while the right grid has 300 dp width. Code can be found <a href="https://gist.github.com/annoyinglemon/192d92fd8bef822e0c38426a94571d0a">here</a>.</figcaption></figure><p>As you can see, the right grid became an eyesore. Item sizes became unidentical due to FlowRow’s behavior and narrow grid width. Also, this cannot be fixed by setting Modifier.fillMaxSize (or <em>.</em>fillMaxHeight<em>)</em><strong><em> </em></strong>to each item as it has no effect. The docs for fillMaxSize<em> </em>says:</p><blockquote>If the incoming maximum width or height is Constraints.<strong>Infinity</strong> this modifier will have no effect in that dimension.</blockquote><p>fillMaxSize having no effect makes sense since each grid item can take as much height as it needs because LazyVerticalGrid does not restrict its items to a specific height. LazyVerticalGrid will take care of its items’ width since I want a fixed number of columns so no problems with that. However, if we want our items to have identical heights, these are the possible solutions ( comment if you have more ideas :D ).</p><ul><li>Define the item’s height using Modifier.height</li><li>Define the item’s width and height ratio by using Modifier.aspectRatio</li><li>Create a custom grid combining columns and rows, then define the height of rows using Modifier.height<em>. </em>Finally, use .fillMaxHeight to items.</li></ul><p>I did not opt-in to any solutions above since I want to ensure that the items’ contents are fully visible while such items have identical sizes. I also want my grid to be flexible on various width sizes as much as possible. In the worst-case scenario, the screen width is as narrow as a TV remote (since my grid will always fill the screen’s width), in that case, item contents might become unreadable, but that’s a problem for later :P</p><p>If I want all my items to have identical heights, then I need to obtain the height of the tallest item, given that this item is placed on the screen with its contents. Then, apply the obtained height to all other items. Is there a way to measure each grid item and then apply the measurements upon composition? <strong>YES!!</strong></p><h3>Behold, the SubcomposeLayout</h3><p>SubcomposeLayout<em> </em>allows us to “subcompose” the actual contents during the measuring stage so that we can use the calculated measurements as params for its children’s composition. As of this moment, I couldn&#39;t find the definition of the term “subcompose” in the docs so please do not hesitate to put it in the comments if you do find it :D . I assume “subcomposition” differs from “composition” in that the former composes composables onto a layout plane but not for displaying purposes but for measurement purposes. I may be wrong but that’s how I view it, correct me in the comments if I’m wrong. That being said, “subcomposition” still involves drawing within a constraint, like screen size, the parent’s size, or a specific size.</p><p>According to the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/package-summary#SubcomposeLayout(androidx.compose.ui.Modifier,kotlin.Function2)">docs</a>, SubcomposeLayout has 3 possible use cases, one of them is this one:</p><blockquote>You want to use the size of one child during the composition of the second child.</blockquote><p>This fits our use case since we want to apply the height of the tallest grid item to all other items so that they’ll have identical heights. To measure such height, we have to take a look at how SubcomposeLayout works.</p><h4>A basic SubcomposeLayout structure</h4><pre>@Composable<br>fun ExampleSubcomposeLayout(<br>    modifier: Modifier = Modifier,<br>    layoutContent: @Composable () -&gt; Unit,<br>) {<br>    // 1<br>    SubcomposeLayout(modifier) { constraints -&gt; <br>        // 2<br>        val measurables = subcompose(&quot;some_id&quot;) { layoutContent() }  <br>        // 3<br>        val placeables = measurables.map {<br>            it.measure(<br>                Constraints(<br>                    maxWidth = constraints.maxWidth / measurables.size,<br>                    minWidth = constraints.maxWidth / measurables.size,<br>                )<br>            )<br>        }<br>        val tallestHeight = placeables.maxOf { it.height }<br>        // 4<br>        layout(constraints.maxWidth, tallestHeight) {<br>            var xOffset = 0<br>            placeables.forEach { it<br>                it.placeRelative(xOffset, 0)<br>                xOffset += it.width<br>            }<br>        }<br>    }<br>}</pre><p>ExampleSubcomposeLayout method above utilizes SubcomposeLayout to display the layoutContent composable param. It accepts the usual Modifier for SubcomposeLayout use. Here’s how this function work.</p><ol><li>Here we declare the SubcomposeLayout passing our modifier. The other params are SubcomposeLayoutState and <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/SubcomposeMeasureScope">SubcomposeMeasureScope</a>.(Constraints) -&gt; MeasureResult . We will not talk about SubcomposeLayoutState as this topic might get more complex. The latter parameter is a function param that provides a<a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Constraints">Constraints</a>object. Constraints is a class that contains properties (min/max height/width) that limit child composables’ size. This function param should return a <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/MeasureResult">MeasureResult</a> that is done by the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/MeasureScope#layout(kotlin.Int,kotlin.Int,kotlin.collections.Map,kotlin.Function1)">layout()</a> function.</li><li>Here we create our List of <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/Measurable">Measurable</a>s using the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/SubcomposeMeasureScope#subcompose(kotlin.Any,kotlin.Function0)">subcompose()</a> function. This function is the main reason why we would use a SubcomposeLayout. subcompose() performs the subcomposition of composables. The composables that are subject to subcomposition must be invoked within its content function param. The content function param could emit multiple composables, in that case the returned list of Measurables will have multiple elements. For example, layoutContent has 3 Text composables within it like <a href="https://gist.github.com/annoyinglemon/46716076f9955dbe9f0bc892f9ed3f24">this one</a>. Then the returned List&lt;Measurables&gt; will contain 3 Measurables, one for each Text. subcompose() can be invoked multiple times, in that case a uniqueslotId (of Any? type) must be supplied to avoid IllegalArgumentException. In our case above, I need to measure the ExampleSubcomposeLayout‘s layoutContent so I invoked it within the subcompose()&#39;scontent lambda.</li><li>Here we convert each Measureable into a <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/Placeable">Placeable</a>. This is where the actual measurement is happening. To measure a Measurable, we need to invoke<a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/Measurable#measure(androidx.compose.ui.unit.Constraints)">measure()</a>, passing in a <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/unit/Constraints">Constraints</a>object. The measure() function will then use the provided Constraints object to limit the size of the Measurable being measured. If the measurement is a success, this function returns a Placeable that contains sizing data such as measuredHeight and measuredWidth. In the example above, I want to equally divide the width of my SubcomposeLayout’s width (by using its constraint) to each of my Measurables. Each of my Measurable has now a fixed width since I set both minWidth and maxWidth of the provided Constraints object.</li><li>In this last part, we finally layout and place our Placeables. In this phase, the composables are already drawn using subcompose(), they just need to be placed. We can do that using the <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/MeasureScope#layout(kotlin.Int,kotlin.Int,kotlin.collections.Map,kotlin.Function1)">layout()</a> function. The parameters I passed determined the size of the layout. The first parameter is for width, so I passed constraints.maxWidth which should resemble the SubcomposeLayout’s width. While the second is for height, so I passed in the tallest child’s height. Then the third parameter is a <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/Placeable.PlacementScope">Placeable.PlacementScope</a>.() -&gt; Unit lambda, inside it is where we place ourPlaceables. There are many functions to choose from when placing, but I chose <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/Placeable.PlacementScope#(androidx.compose.ui.layout.Placeable).placeRelative(androidx.compose.ui.unit.IntOffset,kotlin.Float)">placeRelative</a> since it reacts to RTL layout unlike <a href="https://developer.android.com/reference/kotlin/androidx/compose/ui/layout/Placeable.PlacementScope#(androidx.compose.ui.layout.Placeable).place(kotlin.Int,kotlin.Int,kotlin.Float)">place</a>. Then with the traditional XY coordinates system, I placed each Placeable.</li></ol><h4>SubcomposeLayout in action</h4><p>Take a good look at the code above and analyze how ExampleSubcomposeLayout would look if we pass <a href="https://gist.github.com/annoyinglemon/46716076f9955dbe9f0bc892f9ed3f24">this</a> as our layoutContent. If you assume that it will arrange the texts in a horizontal manner while having equal widths, then you are correct. This is the same as using a Row while giving each text a weight of 1f. Here’s what it looks like on Preview.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r4AuDQmX5ljm3ijyBB4luQ.png" /><figcaption>ExampleSubcomposeLayout Preview, code <a href="https://gist.github.com/annoyinglemon/07b868c6bce833c1fed649703c28f7be">here</a></figcaption></figure><p>Let’s update our ExampleSubcomposeLayout so that it displays the texts in several ways and satisfies the following use cases.</p><ul><li><strong>Display the texts horizontally, imitating a </strong><strong>Row. Each text consumes only its required width. Layout size should wrap the contents.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*klJibhUDhAIXeyjD3AEAdw.png" /></figure><pre>SubcomposeLayout(modifier) { constraints -&gt;<br>    val measurables = subcompose(&quot;some_id&quot;) { layoutContent() }<br>    val placeables = measurables.map {<br>        // maxWidth and maxHeight is Constraints.Infinity, it can use as much width/height as it wants<br>        it.measure(Constraints()) <br>    }<br>    // total width of texts, for layout&#39;s width<br>    val totalWidth = placeables.sumOf { it.width }<br>    val tallestHeight = placeables.maxOf { it.height }<br>    layout(totalWidth, tallestHeight) {<br>        var xOffset = 0<br>        placeables.forEach { it<br>            it.placeRelative(xOffset, 0)<br>            xOffset += it.width<br>        }<br>    }<br>}</pre><ul><li><strong>Display the texts vertically, imitating a </strong><strong>Column . Layout size should wrap the contents.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqVxvUgMPmyJZLr7jMNDrQ.png" /></figure><pre>SubcomposeLayout(modifier) { constraints -&gt;<br>    val measurables = subcompose(&quot;some_id&quot;) { layoutContent() }<br>    val placeables = measurables.map {<br>        it.measure(constraints) // provide the parent&#39;s constraints<br>    }<br>    val longestWidth = placeables.maxOf { it.width } // find longest child<br>    val totalHeight = placeables.sumOf { it.height } // sum of children&#39;s heights<br>    layout(longestWidth, totalHeight) {<br>        var yOffset = 0 <br>        placeables.forEach {<br>            it.placeRelative(0, yOffset)<br>            yOffset += it.height // use the height of each child to adjust the next child&#39;s placement<br>        }<br>    }<br>}</pre><ul><li><strong>Reduce each text’s width to half of the longest text’s width. Imitate a </strong><strong>Column, layout size should wrap the contents.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x883KsUscCxc-_eJD863Rw.png" /></figure><pre>SubcomposeLayout(modifier) { constraints -&gt;<br>    // measure each child composable<br>    val placeables = subcompose(&quot;id&quot;) {<br>        layoutContent()<br>    }.map { it.measure(Constraints()) } // Infinity constraint<br>    val longestWidth = placeables.maxOf { it.width } // get longest text<br>    // pass another id to avoid IllegalArgumentException<br>    val resizedPlaceables = subcompose(&quot;resized&quot;) {<br>        layoutContent()<br>    }.map { <br>        // convert to measurable, passing half the longest text&#39;s width<br>        it.measure(<br>            Constraints(<br>                minWidth = longestWidth / 2,<br>                maxWidth = longestWidth / 2<br>            )<br>        )<br>    }<br>    // get longest width of resized Placeable<br>    val longestResizedWidth = resizedPlaceables.maxOf { it.width }<br>    val totalHeight = resizedPlaceables.sumOf { it.height }<br>    layout(longestResizedWidth, totalHeight) {<br>        var yOffset = 0<br>        resizedPlaceables.forEach {<br>            it.placeRelative(0, yOffset)<br>            yOffset += it.height<br>        }<br>    }<br>}</pre><h3>Solving the Problem</h3><p>Now that we are now familiar with how does aSubcomposeLayout work, let’s now solve our problem!</p><blockquote>I need to obtain the height of the tallest item, given that this item is placed on the screen with its contents. Then, apply the obtained height to all other items.</blockquote><p>The following topics are the things I considered while building this custom vertical grid. Each topic has some code and explanation accompanying it to make it understandable. Let’s name our new composable CustomVerticalGrid.</p><h4>Content padding</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlnrDBLlO14Ye5f97se8rQ.png" /></figure><p>CustomVerticalGrid most likely will have some padding for its item content. This can be solved by passing PaddingValues as a parameter. Then inside the SubcomposeLayout‘s block, calculate the side paddings.</p><pre>@Composable<br>fun CustomVerticalGrid(<br>    modifier: Modifier = Modifier,<br>    contentPadding: PaddingValues = PaddingValues(16.dp),<br>    ...<br>) {<br>    val layoutDirection = LocalLayoutDirection.current<br>    SubcomposeLayout(modifier) { constraints -&gt;<br>        val bottomPadding = contentPadding.calculateBottomPadding().roundToPx()<br>        val leftPadding = contentPadding.calculateLeftPadding(layoutDirection).roundToPx()<br>        val rightPadding = contentPadding.calculateRightPadding(layoutDirection).roundToPx()<br>        val topPadding = contentPadding.calculateTopPadding().roundToPx()<br>        ....<br>    }<br>} </pre><h4>Spacing between Rows and Columns</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DpXeprH9ExWXuqWfCgusVA.png" /></figure><p>CustomVerticalGrid‘s items most likely will have some spacing between them. Let’s add them as Dp params and convert them to pixels.</p><pre>@Composable<br>fun CustomVerticalGrid(<br>    ...<br>    horizontalSpacing: Dp = 12.dp,<br>    verticalSpacing: Dp = 12.dp,<br>    ...<br>) {<br>    val layoutDirection = LocalLayoutDirection.current<br>    SubcomposeLayout(modifier) { constraints -&gt;<br>        ...<br>        val horizontalSpace = horizontalSpacing.roundToPx()<br>        val verticalSpace = verticalSpacing.roundToPx()<br>        ... <br>    }<br>}</pre><h4>Item Width</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cr0esjf1F4aFbcw7FYjnog.png" /></figure><p>Item widths should be equal. To get the exact width needed, we have to find the sum of all spaces (in-between and horizontal padding), then deduct that sum from the layout’s width. Finally, the difference is divided by the number of columns. The resulting width can finally be used to subcompose each element so that we can find the tallest’s item height.</p><pre>@Composable<br>fun &lt;E&gt; CustomVerticalGrid(<br>    modifier: Modifier = Modifier,<br>    numberOfColumns: Int = 2,<br>    contentPadding: PaddingValues = PaddingValues(16.dp),<br>    horizontalSpacing: Dp = 12.dp,<br>    elements: List&lt;E&gt;,<br>    gridItem: @Composable (E) -&gt; Unit,<br>) {<br>    val layoutDirection = LocalLayoutDirection.current<br>    SubcomposeLayout(modifier) { constraints -&gt;<br>        ...<br>        val leftPadding = contentPadding.calculateLeftPadding(layoutDirection).roundToPx()<br>        val rightPadding = contentPadding.calculateRightPadding(layoutDirection).roundToPx()<br>        val horizontalSpace = horizontalSpacing.roundToPx()<br>        ...<br>        val totalSpacesWidth = leftPadding + rightPadding + (horizontalSpace * (numberOfColumns - 1))<br>        // calculate the maximum width a grid item can take<br>        val itemWidth = (constraints.maxWidth - totalSpacesWidth) / numberOfColumns<br>        val placeables = elements.map { e -&gt;<br>            subcompose(e) {<br>                // content param could emit multiple layouts, we use Box to ensure only one layout is emitted<br>                Box(Modifier.width(itemWidth.toDp())) { gridItem(e) }<br>            }<br>            .first() // get the first and only Measurable from each item<br>            .measure(Constraints()) // measure the Measurable to obtain a Placeable from each item<br>        }<br>        ...<br>  }<br>}</pre><h4>Item Height</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Vy25qWYAmqXI8rXYH4iJQ.png" /></figure><p>As you might notice from the previous topic above, measuring the subcomposed items converts them into Placeables. To find the tallest height, we can use Placeable’s height property. We will use this tallest height to lay out our items later</p><pre>...<br>val itemHeight = placeables.maxOf { it.height }<br>...</pre><h4>Laying out the items</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9OhyQuB6Bd4SzK2DYW3TIQ.png" /></figure><p>I want my items to adapt to their parent’s height and avoid unexpected scrolling behavior. To do this, we first have to check if our SubcomposeLayout has a fixed height or not. It has a fixed height if fillMaxSize, fillMaxHeight, or any function that sets its height is used on its Modifier. Otherwise, I want SubcomposeLayout to wrap my items. To verify if SubcomposeLayout has a fixed height, we can use its constraints’ hasBoundedHeight property. Then use the necessary constraints to lay out our items.</p><pre>@Composable<br>fun &lt;E&gt; CustomVerticalGrid(...) {<br>    ...<br>    SubcomposeLayout(modifier) { constraints -&gt;       <br>        ...<br>        val itemsTotalHeight = (placeables.size / numberOfColumns).run {<br>            val numberOfRows = if (placeables.size % numberOfColumns == 0) this else this + 1<br>            itemHeight * numberOfRows<br>        }<br>        val spacesTotalHeight = (placeables.size / numberOfColumns).run {<br>            val numberOfSpaces = if (placeables.size % numberOfColumns == 0) this - 1 else this<br>            (numberOfSpaces * verticalSpace) + topPadding + bottomPadding<br>        }<br>        val totalGridHeight = itemsTotalHeight + spacesTotalHeight<br>        val gridConstraints = getGridConstraints(constraints = constraints, totalCalculatedHeight = totalGridHeight)<br>        // place the Grid itself<br>        if (!constraints.hasBoundedHeight) {<br>            // if this composable&#39;s maxHeight is not defined (or infinity) then place the items in a grid manner<br>            layoutCustomVerticalGrid(<br>                gridConstraints = gridConstraints,<br>                numberOfColumns = numberOfColumns,<br>                horizontalSpace = horizontalSpace,<br>                leftPadding = leftPadding,<br>                topPadding = topPadding,<br>                verticalSpace = verticalSpace,<br>                elements = elements,<br>                gridItem = gridItem,<br>                itemHeight = itemHeight,<br>                itemWidth = itemWidth,<br>            )<br>        } else {<br>            // if this composable&#39;s maxHeight is defined then utilize LazyVerticalGrid<br>            layoutLazyVerticalGrid(<br>                gridConstraints = gridConstraints,<br>                numberOfColumns = numberOfColumns,<br>                contentPadding = contentPadding,<br>                horizontalSpacing = horizontalSpacing,<br>                verticalSpacing = verticalSpacing,<br>                elements = elements,<br>                gridItem = gridItem,<br>                itemHeight = itemHeight,<br>            )<br>        }<br>    }<br>}</pre><pre>/**<br> *  Returns the [Constraints] to be used on the grid. The returned [Constraints] may depend on the<br> *  parent [constraints] and the total calculated height needed for resulting grid. The resulting<br> *  constraints will be used on layout phase.<br> */<br>private fun getGridConstraints(<br>    constraints: Constraints,<br>    totalCalculatedHeight: Int,<br>): Constraints {<br>    return if (!constraints.hasBoundedHeight) {<br>        // if this parent composable&#39;s maxHeight is not defined (Infinity) then<br>        // use the calculated totalHeight as the grid height.<br>        Constraints(<br>            minHeight = totalCalculatedHeight,<br>            maxHeight = totalCalculatedHeight,<br>            minWidth = constraints.minWidth,<br>            maxWidth = constraints.maxWidth,<br>        )<br>    } else {<br>        // use the parent&#39;s constraint as its height is defined (or fills its parent)<br>        constraints<br>    }<br>}</pre><p>This is the result! Our CustomVerticalGrid on the left fills its parent size while the one on the right is inside a column along with other contents. Items sizes are identical too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*U9GtJwZI-wkQHxVs9-mQxw.gif" /></figure><p>That’s it! Thank you for taking the time to read this long post. If you want to view the full working code, you can view it <a href="https://gist.github.com/annoyinglemon/51a8dcac8915a30b41fd7fb03ac0cbd6">here</a>.</p><p>Post your question or comment if you have one. Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0249f033d16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Migrating Jacoco reports Gradle tasks to Kotlin DSL]]></title>
            <link>https://medium.com/@kurtlemond/migrating-jacoco-reports-gradle-tasks-to-kotlin-dsl-7b566d89ea92?source=rss-708c4d82f76e------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b566d89ea92</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[gradle-kotlin-dsl]]></category>
            <category><![CDATA[gradle]]></category>
            <dc:creator><![CDATA[Kurt Lemond Capatan]]></dc:creator>
            <pubDate>Tue, 12 Jul 2022 14:54:29 GMT</pubDate>
            <atom:updated>2022-07-14T13:22:19.527Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, this is not a guide for migrating Gradle Groovy to Gradle Kotlin in general. I just like to share my experience on migrating a specific file. If you’re new to Gradle Kotlin DSL, there’s a ton of other resources out there. :)</p><p>After years of hiding, I decided to dive into Gradle Kotlin and migrate our Android template’s Gradle files to Kotlin DSL. While doing so, I stumbled upon a file named <strong><em>jacoco.gradle</em></strong><em>.</em></p><p>As the file name implies, this script file is being used as a <a href="https://docs.gradle.org/current/userguide/plugins.html#sec:script_plugins">plugin</a> by our module’s <em>build.gradle</em> so that the module can generate code coverage reports in XML and HTML (and also print the results in the terminal). By entering the below commands, such reports can be generated.</p><pre>./gradlew testDebugUnitTestCoverage</pre><h3>What does this jacoco.gradle file do, really?</h3><p>Like I said before, it is for generating test coverage reports. But before diving into details, let’s look at the contents of <em>jacoco.gradle </em>script. (Warning: it’s pretty long)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07f89aaba7a18bec560e107ededb5ccf/href">https://medium.com/media/07f89aaba7a18bec560e107ededb5ccf/href</a></iframe><p><strong>TLDR</strong>: This script combines both product flavors and build types to create Gradle tasks that run unit test and tabulate coverage results on each combination source set.</p><p>That being said, this script depends on each source set’s unit test task and can be ran using <strong><em>test{source_set}UnitTestCoverage</em></strong>. For example, <em>buid.gradle</em> has <em>free</em> and <em>premium</em> flavors and has <em>debug</em> and <em>release</em> build types. The following Gradle commands are executable.</p><p>./gradlew testFreeDebugUnitTestCoverage <br>./gradlew testFreeReleaseUnitTestCoverage <br>./gradlew testPaidDebugUnitTestCoverage <br>./gradlew testPaidReleaseUnitTestCoverage</p><p><em>jacoco.gradle </em>is used as a plugin for the module’s<em> </em><em>build.gradle. </em><em>build.gradle</em> also defines the minimum test coverage required by using <a href="https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties">extra properties</a>. When this minimum requirement is not met, the build should throw a GradleException.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EAeVNMiDNuehho1x_mULgg.png" /><figcaption>jacoco.gradle file location within the project</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cfe94323e4ae8e3ca35adf6ad75d16d/href">https://medium.com/media/6cfe94323e4ae8e3ca35adf6ad75d16d/href</a></iframe><p>If Gradle builds successfully using one of the commands above, the module should generate XML and HTML files for viewing. The XML generated is also parsed so that Gradle can log the result on the terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*jv4pTZt1b00EStLJKLNOpg.png" /><figcaption>Generated jacoco result files for Debug and Local buildTypes</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TteXMcHrjmCXVFMrLhxChQ.png" /><figcaption>XML generated by Jacoco (package nodes are collapsed)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nboDO4BRydExG6MC5Prfvg.png" /><figcaption>Coverage met the required minimum</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vt9ZGkXAm4WKyve_TDTOGA.png" /><figcaption>Coverage has not met the required minimum, 100% in this case</figcaption></figure><p>To summarize, these functionalities should still be working after <em>build.gradle</em> and <em>jacoco.gradle</em> are migrated to Kotlin DSL.</p><ul><li><em>jacoco.gradle</em> can be used as a plugin by <em>build.gradle</em></li><li>Minimum code coverage requirement can be defined in percent</li><li>Run unit tests and generate XML and HTML files for coverage results</li><li>Parse and print the coverage results on the terminal</li><li>Throw GradleException if the test coverage requirements are not met</li></ul><h3>The Migration</h3><p>Renaming <em>jacoco.gradle </em>to <em>jacoco.gradle.kts</em> is not enough (I barely call it a migration). Even if you followed Android Studio lint errors, you might still be bombarded with <em>Unresolved reference</em> errors. This is because dynamic resolution, which Groovy DSL provides, does not exists in Kotlin DSL. Kotlin DSL instead provides type-safe model accessors which replaces Groovy’s dynamic resolution. Kotlin DSL generates static extensions for accessors like android {}<em> </em>or dependencies {} blocks when the plugin {} block is evaluated. Below is a great take from this <a href="https://proandroiddev.com/sharing-build-logic-with-kotlin-dsl-203274f73013">blogpost</a>.</p><blockquote>plugin { } block is evaluated before the script body and Gradle generates accessors for elements contributed by those plugins. Therefore accessors are not calculated for the elements contributed outside the plugin { } block. Using apply() to add a plugin does not generate accessors because apply() is part of the script body.</blockquote><blockquote>Accessors are also <strong>not</strong> available in init scripts (init.gradle.kts), settings scripts (settings.gradle.kts), binary plugins and <strong>script</strong> plugins.</blockquote><p>In our case, we need to access both android.buildTypes and android.productFlavors in jacoco.gradle.kts. Even though we apply com.android.library as a plugin injacoco.gradle.kts (given this file’s location does not change), static extensions will <strong>not</strong> be generated still because jacoco.gradle.ktsis a script plugin.</p><p>There are two ways to solve this.</p><ul><li>convert jacoco.gradle to a <strong>Binary</strong> plugin</li><li>convert jacoco.gradle to a <strong>Precompiled</strong> script plugin</li></ul><h4>Conversion to Binary Plugin</h4><ol><li>Binary plugins are custom plugins that implement the <a href="https://docs.gradle.org/current/javadoc/org/gradle/api/Plugin.html">Plugin interface</a>. Create this plugin file inside the <em>buildSrc</em> directory package.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*B2jF6dVAlYbYk6l7hQTIGg.png" /></figure><p>2. In <em>buildSrc</em>/<em>build.gradle.kts</em>, add the necessary dependencies to be used by the custom plugin. In this case, Android gradle and Kotlin Gradle.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28b9b7af00c152f681f899407d657e3d/href">https://medium.com/media/28b9b7af00c152f681f899407d657e3d/href</a></iframe><p>3. Migrate the existing <em>jacoco.gradle</em> logic scripts to the new plugin class. You may delete <em>jacoco.gradle</em> after migration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a96ea15d77cccffa9a5122c318c1dc35/href">https://medium.com/media/a96ea15d77cccffa9a5122c318c1dc35/href</a></iframe><p>4. Register the custom plugin in <em>buildSrc</em>/<em>build.gradle.kts</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba987a33e39a86a8277d15d958fa0d50/href">https://medium.com/media/ba987a33e39a86a8277d15d958fa0d50/href</a></iframe><p>5. Finally, use the new plugin by applying it to a module’s build.gradle.kts. Declare the necessary minimum test requirement as well via extra properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1652280f5ce98074e1894c465ab50fab/href">https://medium.com/media/1652280f5ce98074e1894c465ab50fab/href</a></iframe><h4>Conversion to Precompiled Script Plugin</h4><ol><li>Add kotlin-dsl-precompiled-script-plugins plugin to buildSrc/build.gradle.kts. Add also the necessary dependencies to be used by the precompiled script.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a2bdefe80fab9f42d276ab5be3f3961/href">https://medium.com/media/8a2bdefe80fab9f42d276ab5be3f3961/href</a></iframe><p>2. Create a precompiled Gradle script file in <em>buildSrc/src/main/kotlin</em> package. Let’s name it <em>jacoco-reports.gradle.kts .</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*tzgcS1wsuMLCEPR7tmlptA.png" /></figure><p>3. Migrate the existing <em>jacoco.gradle</em> logic scripts to the new Gradle KTS file. You may delete <em>jacoco.gradle</em> after migration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/274efea6b102c6928b3d4d298864c2e2/href">https://medium.com/media/274efea6b102c6928b3d4d298864c2e2/href</a></iframe><p>4. Finally, use the new script plugin by applying it to a module <em>build.gradle.kts</em> via its filename, <em>jacoco-reports</em>. Declare the necessary minimum test requirement as well via extra properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6458f868caa1e5775d324c27af9d5526/href">https://medium.com/media/6458f868caa1e5775d324c27af9d5526/href</a></iframe><p>After following either of the solutions above, try executing a Jacoco Gradle task like <em>testDebugUnitTestCoverage.</em> If everything works fine then the code coverage results should print in your terminal.</p><p>I opt into using the Binary plugin because I’m more used to manipulating <em>.kt</em> files than <em>.kts</em> files. While implementing the precompiled script plugin, I found myself relocating some variables just to satisfy the script. Other than that they’re both in Kotlin so both should be convenient to manage.</p><p>That’s it! Thank you for getting this far! I know this is too long of a blog post. If you have questions, improvements, or concerns, let me know in the comments.</p><p>References:</p><ul><li><a href="https://www.eclemma.org/jacoco/">https://www.eclemma.org/jacoco/</a></li><li><a href="https://docs.gradle.org/current/userguide/jacoco_plugin.html">https://docs.gradle.org/current/userguide/jacoco_plugin.html</a></li><li><a href="https://docs.gradle.org/current/userguide/migrating_from_groovy_to_kotlin_dsl.html">https://docs.gradle.org/current/userguide/migrating_from_groovy_to_kotlin_dsl.html</a></li><li><a href="https://docs.gradle.org/current/userguide/kotlin_dsl.html#type-safe-accessors">https://docs.gradle.org/current/userguide/kotlin_dsl.html#type-safe-accessors</a></li><li><a href="https://proandroiddev.com/sharing-build-logic-with-kotlin-dsl-203274f73013">https://proandroiddev.com/sharing-build-logic-with-kotlin-dsl-203274f73013</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b566d89ea92" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>