<?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 Marcin Hanas on Medium]]></title>
        <description><![CDATA[Stories by Marcin Hanas on Medium]]></description>
        <link>https://medium.com/@hanas.marc?source=rss-d56ca58b9ffe------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1jtoiGW3w40UO6oGLSjBTA.jpeg</url>
            <title>Stories by Marcin Hanas on Medium</title>
            <link>https://medium.com/@hanas.marc?source=rss-d56ca58b9ffe------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 00:16:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hanas.marc/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[Using LookaheadScope and intermediateLayout for bottom bar inside Compose navigation]]></title>
            <link>https://medium.com/@hanas.marc/using-lookaheadscope-and-intermediatelayout-for-bottom-bar-inside-compose-navigation-e5abd0cb3cdc?source=rss-d56ca58b9ffe------2</link>
            <guid isPermaLink="false">https://medium.com/p/e5abd0cb3cdc</guid>
            <category><![CDATA[bottomappbar]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[compose-navigation]]></category>
            <category><![CDATA[jetpack-compose-animation]]></category>
            <dc:creator><![CDATA[Marcin Hanas]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 22:53:28 GMT</pubDate>
            <atom:updated>2024-01-30T22:54:38.768Z</atom:updated>
            <content:encoded><![CDATA[<p>Having home screen with navigation bar (or rail in case of bigger screens) is a common pattern used in Android app design. If our app is using Jetpack Compose, then <a href="https://m3.material.io/components">Material Design</a> libraries provide us with ready-to-use components:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*lTkf61jkZ1GuUrO2" /><figcaption><a href="https://m3.material.io/components/navigation-bar/guidelines">M3 Navigation Bar</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z68-DDOENSqEvt7t" /><figcaption><a href="https://m3.material.io/components/navigation-rail/overview">M3 Navigation Rail</a></figcaption></figure><h3>Simple implementation</h3><p>Creating a bottom bar navigation system in Jetpack Compose can be implemented using the Scaffold component, which provides a foundational structure for any screen layout. Inside of it we can use the AnimatedContent Composable to switch between different tabs&#39; content with animations that slide in the correct direction.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*TEsi0tZPRiWzBTb57L9sgg.gif" /></figure><p>Let’s dive into the code:</p><pre>enum class Tabs(val label: String) {<br>    A(&quot;A&quot;), B(&quot;B&quot;)<br>}<br><br>@Composable<br>fun NavBarScreen(<br>    contentA: @Composable () -&gt; Unit,<br>    contentB: @Composable () -&gt; Unit<br>) {<br>    var selectedTab by rememberSaveable { mutableStateOf(A) }<br>    Scaffold(<br>        bottomBar = {<br>            NavigationBar {<br>                NavigationBarItem(<br>                    selected = selectedTab == A,<br>                    onClick = { selectedTab = A },<br>                    label = { Text(A.label) },<br>                    icon = { Icon(Icons.Default.Home, A.label) }<br>                )<br>                NavigationBarItem(<br>                    selected = selectedTab == B,<br>                    onClick = { selectedTab = B },<br>                    label = { Text(B.label) },<br>                    icon = { Icon(Icons.Default.Favorite, B.label) }<br>                )<br>            }<br>        }<br>    ) {<br>        AnimatedContent(<br>            targetState = selectedTab,<br>            modifier = Modifier.padding(it).fillMaxSize(),<br>            transitionSpec = { tabsTransition() }<br>        ) { tab -&gt;<br>            when (tab) {<br>                A -&gt; {<br>                    contentA()<br>                }<br>                B -&gt; {<br>                    contentB()<br>                }<br>            }<br>        }<br>    }<br>}<br><br>private fun AnimatedContentTransitionScope&lt;Tabs&gt;.tabsTransition(): ContentTransform {<br>    val direction = when (targetState) {<br>        A -&gt; Right<br>        B -&gt; Left<br>    }<br>    return slideIntoContainer(towards = direction) togetherWith<br>        slideOutOfContainer(towards = direction)<br>}</pre><p>Tabs are represented by an enum class for easy tracking. The currently selected tab is stored using rememberSaveable, ensuring persistence through configuration changes like screen rotation. NavigationBar and NavigationBarItem are components provided by the M3 (or M2) library, which already implement all necessary theming and animations. Transition animations can be easily specified thanks to initialState and targetState provided by AnimatedContentTransitionScope&lt;Tabs&gt;.</p><h4>Potential drawbacks</h4><p>While this snippet works well for tabs with simple logic or tight connection between each other, its biggest drawback is that they share the same Composition scope. This makes it challenging to separate concerns between the tabs. For instance, if we want a separate viewModel for each tab, we cannot scope it down to only the tab it supports. Both viewModels will run regardless of which tab is selected.</p><h3>The solution — Jetpack Compose Navigation</h3><p>The ideal solution in this case is to utilize Jetpack Compose Navigation. This framework allows you to define separate destinations for each tab, enabling better encapsulation and separation of concerns. Each tab, represented as a destination in the navigation graph, operates within its own lifecycle scope. This ensures that if a ViewModel is defined inside that destination, it will be active only when its corresponding tab is selected.</p><p>Let’s look at the code changes:</p><pre>@Composable<br>fun NavBarScreenWithNavHost(<br>    contentA: @Composable () -&gt; Unit,<br>    contentB: @Composable () -&gt; Unit<br>) {<br>    val navController = rememberNavController()<br>    val currentBackStackEntry by navController.currentBackStackEntryAsState()<br>    val currentTab by remember {<br>        derivedStateOf {<br>            currentBackStackEntry?.destination?.route<br>        }<br>    }<br>    Scaffold(<br>        bottomBar = {<br>            NavigationBar {<br>                NavigationBarItem(<br>                    selected = currentTab == A.label,<br>                    onClick = { navController.navigate(A.label) },<br>                    label = { Text(A.label) },<br>                    icon = { Icon(Icons.Default.Home, A.label) }<br>                )<br>                NavigationBarItem(<br>                    selected = currentTab == B.label,<br>                    onClick = { navController.navigate(B.label) },<br>                    label = { Text(B.label) },<br>                    icon = { Icon(Icons.Default.Favorite, B.label) }<br>                )<br>            }<br>        }<br>    ) {<br>        NavHost(<br>            navController = navController,<br>            startDestination = A.label,<br>            modifier = Modifier<br>                .padding(it)<br>                .fillMaxSize()<br>        ) {<br>            composable(A.label) {<br>                contentA()<br>            }<br>            composable(B.label) {<br>                contentB()<br>            }<br>        }<br>    }<br>}</pre><p>The biggest change is replacing AnimatedContent with NavHost — base component of Jetpack Compose Navigation, which serves as the root for the navigation tree. Inside it, we define a destination for each tab. As it uses a NavHostController instance to navigate between destinations, we have to introduce it with the rememberNavController() method. It holds information about the currently selected destination, so we can extract that information and use it instead of the selectedTab object. We also use navController.navigate(…) to switch between cards.</p><p>To add the same swiping animations as before, we simply define them for each destination:</p><pre>NavHost(<br>    navController = navController,<br>    startDestination = A.label,<br>    modifier = Modifier<br>        .padding(it)<br>        .fillMaxSize()<br>) {<br>    composable(<br>        route = A.label,<br>        enterTransition = {<br>            slideIntoContainer(towards = Right)<br>        },<br>        exitTransition = {<br>            slideOutOfContainer(towards = Left)<br>        }<br>    ) {<br>        contentA()<br>    }<br>    composable(<br>        route = B.label,<br>        enterTransition = {<br>            slideIntoContainer(towards = Left)<br>        },<br>        exitTransition = {<br>            slideOutOfContainer(towards = Right)<br>        }<br>    ) {<br>        contentB()<br>    }<br>}</pre><p>This approach works well when we want the navigation bar to be displayed on each screen within an activity. However, in single-activity apps, this implies having the bar present in every screen of the application. A simple solution to address this is to check whether a destination requires the bottom bar and hide it accordingly.</p><pre>@Composable<br>fun NavBarScreenWithNavHost(<br>    contentA: @Composable (NavController) -&gt; Unit,<br>    contentB: @Composable (NavController) -&gt; Unit,<br>    contentC: @Composable (NavController) -&gt; Unit<br>) {<br>    val navController = rememberNavController()<br>    val currentBackStackEntry by navController.currentBackStackEntryAsState()<br>    val currentTab by remember {<br>        derivedStateOf {<br>            currentBackStackEntry?.destination?.route<br>        }<br>    }<br>    Scaffold(<br>        bottomBar = {<br>            val isVisible = currentTab in Tabs.entries.map { it.label }<br>            AnimatedVisibility(isVisible,<br>                enter = fadeIn(),<br>                exit = fadeOut()<br>            ) {<br>                NavigationBar {<br>                    NavigationBarItem(<br>                        selected = currentTab == A.label,<br>                        onClick = { navController.navigate(A.label) },<br>                        label = { Text(A.label) },<br>                        icon = { Icon(Icons.Default.Home, A.label) }<br>                    )<br>                    NavigationBarItem(<br>                        selected = currentTab == B.label,<br>                        onClick = { navController.navigate(B.label) },<br>                        label = { Text(B.label) },<br>                        icon = { Icon(Icons.Default.Favorite, B.label) }<br>                    )<br>                }<br>            }<br>        }<br>    ) {<br>        NavHost(<br>            navController = navController,<br>            startDestination = A.label,<br>            modifier = Modifier.padding(it).fillMaxSize()<br>        ) {<br>            composable(A.label) {<br>                contentA(navController)<br>            }<br>            composable(B.label) {<br>                contentB(navController)<br>            }<br>            composable(&quot;C&quot;) {<br>                contentC(navController)<br>            }<br>        }<br>    }<br>}</pre><p>In the example above, we included a destination <strong>C</strong>, which is intended to not show the bottom bar. While this approach works, it supports only one bottom bar for the entire app.</p><p>If our goal is to use a single NavHost for the entire application, this requires defining the bar at the topmost level of the navigation tree rather than managing it near the home screen code where it logically belongs. This approach introduces several challenges:</p><ol><li>Reduced readability.</li><li>Complexity in adding additional information based on home data into the bottom sheet, such as displaying a badge indicating the number of unread messages or changing navigation items based on the profile type.</li><li>Potential nesting of Scaffolds, as we place one outside of NavHost, and the destinations inside it might require one as well.</li></ol><h4>Nested NavHosts</h4><p>One solution to this problem would be to utilize nested NavHosts: one for the entire app, and inside one of the destinations of this NavHost, introduce another NavHost specifically for the home view area. While this approach helps in separating home view screens from the rest of the application, it unfortunately adds a considerable amount of complexity and does not support Compose Navigation deeplinks. This limitation arises because the library only checks for deeplinks in the external NavGraph.</p><h4>Moving bottom bar to inside of the destinations</h4><p>First of all, we will move navigation bar composable into a separate method to make it reusable. We can remove AnimatedContent, as the general navigation transition will now also be applied to the bottom bar and it won’t be added to any destinations that are not supposed to have it.</p><pre>@Composable<br>private fun HomeNavBar(navController: NavHostController) {<br>    val currentBackStackEntry by navController.currentBackStackEntryAsState()<br>    val currentTab by remember {<br>        derivedStateOf {<br>            currentBackStackEntry?.destination?.route<br>        }<br>    }<br>    NavigationBar {<br>        NavigationBarItem(<br>            selected = currentTab == A.label,<br>            onClick = { navController.navigate(A.label) },<br>            label = { Text(A.label) },<br>            icon = { Icon(Icons.Default.Home, A.label) }<br>        )<br>        NavigationBarItem(<br>            selected = currentTab == B.label,<br>            onClick = { navController.navigate(B.label) },<br>            label = { Text(B.label) },<br>            icon = { Icon(Icons.Default.Favorite, B.label) }<br>        )<br>    }<br>}</pre><p>Next, we’ll incorporate a separate Scaffold within each composable destination and include the bottom bar as a parameter. We could also provide the Scaffold with bottom bar inside the contentA and contentB parameters.</p><pre>@Composable<br>fun NavBarScreenWithBarInsideDestinations(<br>    contentA: @Composable (NavController) -&gt; Unit,<br>    contentB: @Composable (NavController) -&gt; Unit,<br>    contentC: @Composable (NavController) -&gt; Unit<br>) {<br>    val navController = rememberNavController()<br>    NavHost(<br>        navController = navController,<br>        startDestination = A.label,<br>        modifier = Modifier.fillMaxSize()<br>    ) {<br>        composable(<br>            route= A.label,<br>            enterTransition = { slideIntoContainer(towards = Left) },<br>            exitTransition = { slideOutOfContainer(towards = Right) }<br>        ) {<br>            Scaffold(<br>                bottomBar = { HomeNavBar(navController) }<br>            ) {<br>                contentA(navController)<br>            }<br>        }<br>        composable(<br>            route = B.label,<br>            enterTransition = { slideIntoContainer(towards = Right) },<br>            exitTransition = { slideOutOfContainer(towards = Left) }<br>        ) {<br>            Scaffold(<br>                bottomBar = { HomeNavBar(navController) }<br>            ) {<br>                contentB(navController)<br>            }<br>        }<br>        composable(&quot;C&quot;) {<br>            contentC(navController)<br>        }<br>    }<br>}</pre><p>This solution works well, but since bottom bars are now a part of each destination, it gets animated together with entire screen — and we want it to not move horizontally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*bEWUAxoyORmHDlkSfPEQgA.gif" /></figure><h3>Solution with LookaheadScope and intermediateLayout</h3><p>Here comes the solution inspired by <a href="https://newsletter.jorgecastillo.dev/p/introducing-lookaheadlayout">Jorge Castillo’s article</a>. It draws inspiration from shared element transitions, used in Fragment Navigation. This approach utilizes LookaheadScope to be able to calculate positioning of the bottom bar relative to the entire NavHost, rather than just the current destination’s root layout.</p><pre>@Composable<br>fun NavBarScreenWithBarInsideDestinations(<br>    contentA: @Composable (NavController) -&gt; Unit,<br>    contentB: @Composable (NavController) -&gt; Unit,<br>    contentC: @Composable (NavController) -&gt; Unit<br>) {<br>    val navController = rememberNavController()<br>    LookaheadScope {<br>        NavHost(<br>            navController = navController,<br>            startDestination = A.label,<br>            modifier = Modifier.fillMaxSize()<br>        ) { ... }<br>    }<br>}</pre><p>To then recalculate the placement of the bottom bar before it’s drawn, the excludeFromTransitionAnimations Modifier is introduced. It uses the intermediateLayout modifier, which has access to lookaheadScopeCoordinates. By using this information, the modifier calculates the horizontal offset induced by transition animations and adjusts the placement of the bottom bar accordingly. This ensures that the bottom bar appears to remain static during transitions.</p><pre>fun Modifier.excludeFromTransitionAnimations(): Modifier =<br>    intermediateLayout { measurable, constraints -&gt;<br>        val placeable = measurable.measure(constraints)<br>        layout(placeable.width, placeable.height) {<br>            val (x, _) = coordinates?.let { coordinates -&gt;<br>                lookaheadScopeCoordinates.localPositionOf(<br>                    coordinates,<br>                    Offset.Zero<br>                ).round()<br>            } ?: IntOffset.Zero<br>            placeable.place(-x, 0)<br>        }<br>    }</pre><p>Then, we simply need to apply this Modifier to every component that we want to exclude from the transition, whether it&#39;s the bottom bar, navigation rail, or even the profile menu button.</p><pre>@Composable<br>private fun HomeNavBar(navController: NavHostController) {<br>    val currentBackStackEntry by navController.currentBackStackEntryAsState()<br>    val currentTab by remember {<br>        derivedStateOf {<br>            currentBackStackEntry?.destination?.route<br>        }<br>    }<br>    NavigationBar(Modifier.excludeFromTransitionAnimations()) { ... }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*7CUuhC_CI4HGEsDmlccpPw.gif" /></figure><h4>Drawbacks</h4><p>Unfortunately, this solution is not perfect — the ripple animation when clicking on bottom bar element is only triggered on current destination, and not the target destination to which we animate. We could solve it by implementing custom bottom bar with ripple animations that share their state between destinations.</p><p>Considering the advantages and disadvantages of each solution, it’s essential to decide which option aligns best with the specific needs and goals of our application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e5abd0cb3cdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improving accessibility in Android apps]]></title>
            <link>https://medium.com/@hanas.marc/improving-accessibility-in-android-apps-ac638c57a1e8?source=rss-d56ca58b9ffe------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac638c57a1e8</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[talkback]]></category>
            <dc:creator><![CDATA[Marcin Hanas]]></dc:creator>
            <pubDate>Tue, 11 Apr 2023 14:34:01 GMT</pubDate>
            <atom:updated>2023-04-11T14:34:01.273Z</atom:updated>
            <content:encoded><![CDATA[<h4>A Guide to character-by-character text reading with TalkBack in Compose</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKQjJytRnQG2ufZat8uAgA.jpeg" /></figure><p>As developers, it’s essential to develop applications with accessibility in mind. TalkBack is a Google screen reader included on Android devices, which enables users with vision impairments to interact with their devices by listening to spoken feedback. It is supported by default in all Android apps, but sometimes it’s useful to adjust some parts of our app to optimise the user experience of TalkBack feature.</p><h3>Phone number problem</h3><p>One of the issues that I encountered was how TalkBack was reading phone numbers as big numbers. For example, the number <em>111222333</em> would be read as one <em>hundred eleven million, two hundred twelve thousand, three hundred thirteen</em>. While I could have fixed it by changing the format that the number is presented to include spaces or dashes, I decided that it should be read digit-by-digit. Since this isn’t the default behaviour of how TalkBack behaves, I had to add some extra code to achieve this.</p><h3>Compose solution</h3><p>Fortunately, there’s a solution in Compose. While SpannedString has support for TtsSpan with many options, it can’t be used with Composables such as Text, which only use String or AnnotatedString as parameters. However, there is a sealed class TtsAnnotation meant to be used together with AnnotatedString. Currently, it only consists of one child class, VerbatimTtsAnnotation, which is precisely what we need.</p><p>We can use it with a dedicated builder method for AnnotatedString, as shown in the example below:</p><pre>val annotatedString = buildAnnotatedString {<br>    withAnnotation(VerbatimTtsAnnotation(&quot;111222333&quot;)) {<br>        append(&quot;111222333&quot;)<br>    }<br>}<br>Text(text = annotatedString)</pre><p>As this feature is still in experimental phase, we will need to opt in for it with an annotation @OptIn(ExperimentalTextApi::class).</p><p>If we already have a full string (for example from resource values), and only want to add verbatim support for some parts of it, we can implement a more generic solution. It finds position of each word in the code, and then proceeds to add an annotation to them using addTtsAnnotation method inside a builder.</p><pre>private data class AnnotatedSpanData(<br>    val value: String,<br>    val startPosition: Int,<br>    val endPosition: Int<br>)<br><br>@OptIn(ExperimentalTextApi::class)<br>fun Context.getAnnotatedString(@StringRes res: Int, vararg verbatimValues: String): AnnotatedString {<br>    val stringToDecorate = this.getString(res)<br>    val spanPositions = verbatimValues.map { value -&gt;<br>        val startPosition = stringToDecorate.indexOf(value)<br>        val endPosition = startPosition + value.length<br>        AnnotatedSpanData(value, startPosition, endPosition)<br>    }<br>    return buildAnnotatedString {<br>        append(stringToDecorate)<br>        spanPositions.forEach {<br>            if (it.startPosition &gt;= 0 &amp;&amp; it.endPosition &lt;= stringToDecorate.length) {<br>                addTtsAnnotation(VerbatimTtsAnnotation(it.value), it.startPosition, it.endPosition)<br>            }<br>        }<br>    }<br>}</pre><h3>Improving TextField TalkBack experience</h3><p>Another place where character-by-character reading might be useful for visually impaired users of our app is a TextField. By default, the content of a TextField will be read as regular words, but it might be beneficial for the user to hear what they inputted (for example, an email, number, or surname) letter by letter to ensure that it is correct.</p><p>To achieve this, we will once again use the fact that OutlinedTextField uses TextFieldValue, which can take AnnotatedString as its parameter instead of a regular string. For each value of input, we will copy it with added annotation to its text value.</p><pre>var input by remember {<br>    mutableStateOf(TextFieldValue())<br>}<br>val verbatimInput by remember {<br>    derivedStateOf {<br>        input.copy(<br>            annotatedString = buildAnnotatedString {<br>                withAnnotation(VerbatimTtsAnnotation(input.text)) {<br>                    append(input.text)<br>                }<br>            }<br>        )<br>    }<br>}<br>OutlinedTextField(<br>    value = verbatimInput,<br>    label = {<br>        Text(&quot;Test verbatim input field&quot;)<br>    },<br>    onValueChange = { newValue -&gt;<br>        input = newValue<br>    }<br>)</pre><p>In conclusion, by implementing character-by-character text reading with TalkBack in Compose, we can greatly improve the accessibility of our Android apps for users with vision impairments. This small addition can make a big difference in ensuring that all users can interact with our apps in a way that is intuitive and user-friendly. As developers, we have a responsibility to prioritise accessibility in our app development, and this is one simple step that we can take towards creating more inclusive experiences for all users.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac638c57a1e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Intent-Based Compose Navigation]]></title>
            <link>https://medium.com/better-programming/intent-based-compose-navigation-1087634b984a?source=rss-d56ca58b9ffe------2</link>
            <guid isPermaLink="false">https://medium.com/p/1087634b984a</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <category><![CDATA[android-navigation]]></category>
            <dc:creator><![CDATA[Marcin Hanas]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 08:50:43 GMT</pubDate>
            <atom:updated>2023-03-28T17:02:25.679Z</atom:updated>
            <content:encoded><![CDATA[<h4>Exploring Compose’s limits when sending more complex data structures between destinations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OUsN8q72R6l5zqyw" /><figcaption>Photo by <a href="https://unsplash.com/@aaronburden?utm_source=medium&amp;utm_medium=referral">Aaron Burden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When Google introduced support for <a href="https://developer.android.com/jetpack/compose">Jetpack Compose</a> in the <a href="https://developer.android.com/guide/navigation">Navigation component</a>, the limitations of provided solution were quickly discovered by the Android developers community. The one I want to focus on in this article is not being able to send more complex data structures between destinations.</p><h4>The Google way</h4><p>The main composable in the library, responsible for the navigation, is a NavHost. To add a destination to the navigation structure, we need to add a composable (or another component, such as alert) inside of its lambda argument. The method requires a route in a string format and an optional list of navigation arguments.</p><pre>NavHost(startDestination = &quot;profile/{userId}&quot;) {<br>    ...<br>    composable(<br>        &quot;profile/{userId}&quot;,<br>        arguments = listOf(navArgument(&quot;userId&quot;) { type = NavType.StringType })<br>    ) {...}<br>}</pre><p>In the library documentation, we can see the <a href="https://developer.android.com/guide/navigation/navigation-pass-data#supported_argument_types">supported argument types</a>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0zNkleCU3hUV6vZDKntfQ.png" /></figure><p>Unfortunately, only basic ones, such as Integer, Boolean, and String are handled by routes. The needed one for our case, custom Parcelable, while being a part of the library, cannot be used in this situation.</p><p>The actual navigation is done by calling navigate method on navController with a correctly formatted route string that contains all the necessary arguments.</p><pre>navController.navigate(&quot;profile/user1234&quot;)</pre><h4>Google’s reasoning</h4><p>How does Google explain its lack of support for more complex data types for navigation arguments? They simply <a href="https://developer.android.com/jetpack/compose/navigation#retrieving-complex-data">suggest implementing the single source of truth principle</a>, which means that only the minimum necessary information should be passed between destinations, such as id-strings. Then, the rest of the required data should be obtained from a single source of truth in the data layer. While it is true that this approach should be desired, as it prevents any data inconsistencies across the app, it might be hard to achieve in complex apps and complicates refactoring when the current navigation solution in the app allows sending Parcelables.</p><h4>Commonly used solution</h4><p>The most common solution for sending Parcelables requires creating a custom NavType that will support the desired type (as described <a href="https://proandroiddev.com/jetpack-compose-navigation-with-custom-navtype-9b44dd8820e">here</a>). That solves the described problem, but unfortunately is far from perfect. First of all, data must be parsed to and from string, usually using JSON format, which is inefficient. In case of more complex data, the library can throw errors if the JSON string is too long. On top of that, we need to look out for any possible parsing errors and resolve them with, for example, custom parsers.</p><p>Is there any better solution that wouldn’t require parsing data back and forth ourselves? Let’s look into it!</p><h4>Looking under the surface</h4><p>By looking into the documentation and codebase, we quickly discover that the navigation for compose was not built from scratch but rather added to <a href="https://developer.android.com/guide/navigation">Android Jetpack’s Navigation component</a> on top of the existing NavGraph solution used in fragments navigation. You might be thinking:</p><blockquote>Wait! Those do support sending Parcelables! Why didn’t they add it for Compose as well?!</blockquote><p>A simple explanation is that it might have been a deliberate decision to enforce a single source of truth pattern. Let’s see what happens deeper in the code.</p><pre>@JvmOverloads<br>public fun navigate(<br>    route: String,<br>    navOptions: NavOptions? = null,<br>    navigatorExtras: Navigator.Extras? = null<br>) {<br>    navigate(<br>        NavDeepLinkRequest.Builder.fromUri(createRoute(route).toUri()).build(), navOptions,<br>        navigatorExtras<br>    )<br>}</pre><p>When calling the navigate method with a route, we create a NavDeepLinkRequest with the help of a builder. This will provide an Uri that gets created with createRoute method. It transforms route string, so it can be understood when using a deep-link mechanism. This method will be very important in our solution, so remember it for later.</p><pre>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)<br>public fun createRoute(route: String?): String =<br>    if (route != null) &quot;android-app://androidx.navigation/$route&quot; else &quot;&quot;</pre><p>Then, we send it further down the navigation-methods-chain.</p><pre>@MainThread<br>public open fun navigate(<br>    request: NavDeepLinkRequest,<br>    navOptions: NavOptions?,<br>    navigatorExtras: Navigator.Extras?<br>) {<br>    val deepLinkMatch = _graph!!.matchDeepLink(request)<br>    if (deepLinkMatch != null) {<br>        val destination = deepLinkMatch.destination<br>        val args = destination.addInDefaultArgs(deepLinkMatch.matchingArgs) ?: Bundle()<br>        val node = deepLinkMatch.destination<br>        val intent = Intent().apply {<br>            setDataAndType(request.uri, request.mimeType)<br>            action = request.action<br>        }<br>        args.putParcelable(KEY_DEEP_LINK_INTENT, intent)<br>        navigate(node, args, navOptions, navigatorExtras)<br>    } else {<br>        throw IllegalArgumentException(<br>            &quot;Navigation destination that matches request $request cannot be found in the &quot; +<br>                &quot;navigation graph $_graph&quot;<br>        )<br>    }<br>}</pre><p>Inside this navigate method, we try to find a match for a deep link in our NavGraph (it was created by adding NavDestinations with composable methods described earlier). From the match, specific destinations and args in a Bundle are extracted. Then, a deep link key argument is added. Let’s pause here for a moment and explore how it works.</p><p>The matching process starts in a route, NavDestination, and goes through all of its children recursively to find the best one.</p><pre>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)<br>public override fun matchDeepLink(navDeepLinkRequest: NavDeepLinkRequest): DeepLinkMatch? {<br>    // First search through any deep links directly added to this NavGraph<br>    val bestMatch = super.matchDeepLink(navDeepLinkRequest)<br>    // Then search through all child destinations for a matching deep link<br>    val bestChildMatch = mapNotNull { child -&gt;<br>        child.matchDeepLink(navDeepLinkRequest)<br>    }.maxOrNull()<br><br>    return listOfNotNull(bestMatch, bestChildMatch).maxOrNull()<br>}</pre><p>Here the DeepLinkMatch object named newMatch gets created. It consists of destination, args, and a bunch of additional info. The args Bundle is generated in the getMatchingArguments method, where it extracts data from the parametrised query and adds it to the Bundle.</p><pre>@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)<br>public open fun matchDeepLink(navDeepLinkRequest: NavDeepLinkRequest): DeepLinkMatch? {<br>    if (deepLinks.isEmpty()) {<br>        return null<br>    }<br>    var bestMatch: DeepLinkMatch? = null<br>    for (deepLink in deepLinks) {<br>        val uri = navDeepLinkRequest.uri<br>        val matchingArguments =<br>            if (uri != null) deepLink.getMatchingArguments(uri, arguments) else null<br>        val requestAction = navDeepLinkRequest.action<br>        val matchingAction = requestAction != null &amp;&amp; requestAction ==<br>            deepLink.action<br>        val mimeType = navDeepLinkRequest.mimeType<br>        val mimeTypeMatchLevel =<br>            if (mimeType != null) deepLink.getMimeTypeMatchRating(mimeType) else -1<br>        if (matchingArguments != null || matchingAction || mimeTypeMatchLevel &gt; -1) {<br>            val newMatch = DeepLinkMatch(<br>                this, matchingArguments,<br>                deepLink.isExactDeepLink, matchingAction, mimeTypeMatchLevel<br>            )<br>            if (bestMatch == null || newMatch &gt; bestMatch) {<br>                bestMatch = newMatch<br>            }<br>        }<br>    }<br>    return bestMatch<br>}</pre><p>After we obtained all the necessary data, yet another navigate method gets called. Here’s what that looks like:</p><pre>@MainThread<br>private fun navigate(<br>    node: NavDestination,<br>    args: Bundle?,<br>    navOptions: NavOptions?,<br>    navigatorExtras: Navigator.Extras?<br>) {...}</pre><h4>Sum up of the deep dive</h4><p>The library does the following steps along the way:</p><ul><li>Creates a NavDeepLinkRequest with a formatted route</li><li>Extracts arguments from the route and adds them to the bundle</li><li>Finds the best NavDestination for a given request</li><li>Calls the navigate method, which takes NavDestination and Bundle? as its’ parameters</li></ul><p>Could we then omit the route-parsing part of the implementation and call the last navigate method directly? That way, we could pass a Bundle, which we populate with Parcelable ourselves. Unfortunately, while all the previous navigates are public, this one is private.</p><h4>Let’s get back to the surface</h4><p>Not all hope is lost, though, because by looking at the usages of the desired method, we can see it is used in another navigate method:</p><pre>@MainThread<br>public open fun navigate(<br>    @IdRes resId: Int,<br>    args: Bundle?,<br>    navOptions: NavOptions?,<br>    navigatorExtras: Navigator.Extras?<br>)</pre><p>You might be familiar with it if you have ever used this library for navigating between fragments with navGraph. With this discovery, some questions have popped up in my mind:</p><ul><li>It is public and takes arguments in a Bundle format, so could we use it for our Compose navigation?</li><li>What is the resId in this method, and how could we transform the route string into it?</li></ul><p>The answer for both of them is, fortunately, yes!</p><h4>The search for resId and route string common thread</h4><p>When navGraph gets created in the compose addition of the library, the NavDestinations are added to it with composable methods. If we look closer into its implementation, we can see that the route is applied with its setter method.</p><pre>/**<br> * Add the [Composable] to the [NavGraphBuilder]<br> *<br> * @param route route for the destination<br> * @param arguments list of arguments to associate with destination<br> * @param deepLinks list of deep links to associate with the destinations<br> * @param content composable for the destination<br> */<br>public fun NavGraphBuilder.composable(<br>    route: String,<br>    arguments: List&lt;NamedNavArgument&gt; = emptyList(),<br>    deepLinks: List&lt;NavDeepLink&gt; = emptyList(),<br>    content: @Composable (NavBackStackEntry) -&gt; Unit<br>) {<br>    addDestination(<br>        ComposeNavigator.Destination(provider[ComposeNavigator::class], content).apply {<br>            this.route = route<br>            arguments.forEach { (argumentName, argument) -&gt;<br>                addArgument(argumentName, argument)<br>            }<br>            deepLinks.forEach { deepLink -&gt;<br>                addDeepLink(deepLink)<br>            }<br>        }<br>    )<br>}</pre><p>The setter sets not only the route value but also the id of the NavDestination. This is the same value used to find a matching destination when navigating with the resId argument. With that knowledge, we can easily transform the route into an id and then use Bundles to pass arguments between destinations!</p><pre>/**<br> * The destination&#39;s unique route. Setting this will also update the [id] of the destinations<br> * so custom destination ids should only be set after setting the route.<br> */<br>public var route: String? = null<br>    set(route) {<br>        if (route == null) {<br>            id = 0<br>        } else {<br>            require(route.isNotBlank()) { &quot;Cannot have an empty route&quot; }<br>            // the transformation from route to id<br>            val internalRoute = createRoute(route)<br>            id = internalRoute.hashCode()<br>            addDeepLink(internalRoute)<br>        }<br>        deepLinks.remove(deepLinks.firstOrNull { it.uriPattern == createRoute(field) })<br>        field = route<br>    }</pre><h3>Let’s Create a Solution Out of the Findings</h3><p>Bingo! Now we can test if it works as desired and develop a solution. Let’s start by creating our own navigate method that takes the route String and Bundle as arguments and transforms the route into resId with what we discovered.</p><pre>data class ParcelableClass(...) : Parcelable<br><br>fun NavHostController.navigate(route: String, bundle: Bundle = Bundle()) {<br>    val r = createRoute(route)<br>    navigate(r.hashCode(), bundle)<br>}<br><br>...<br>    val navController = rememberNavController()<br>    NavHost(<br>        navController = navController,<br>        startDestination = &quot;first&quot;,<br>    ) {<br>    composable(&quot;first&quot;) {<br>        ....<br>        Button(onClick = {<br>            val params = bundleOf(<br>                &quot;name&quot; to &quot;Max&quot;,<br>                &quot;data&quot; to ParcelableClass(...)<br>            )<br>            navController.navigate(&quot;second&quot;, params)<br>        }) {...}<br>    }<br>    composable(&quot;second&quot;) {<br>        ....<br>    }<br>...</pre><h4>Retrieving arguments in a composable</h4><p>It can then navigate from the first to the second composable with a name parameter. How can we extract those parameters inside the second screen? If we look closer at the composable method, it has one parameter inside the lambda argument — NavBackStackEntry. We can retrieve arguments from it.</p><pre>composable(&quot;second&quot;) { navBackStackEntry -&gt;<br>    val args: Bundle? = navBackStackEntry.arguments<br>    val name = args?.getString(&quot;name&quot;) // assigns &quot;Max&quot; in the example<br>}</pre><p>The first passed argument was a string, so we can retrieve it with getString method. For the ParcelableClass arg, we need a bit more complex solution to consider that the old getParcelable method is depreciated starting from android Tiramisu.</p><pre>val args: Bundle? = navBackStackEntry.arguments<br>val data: ParcelableClass? = args?.let {<br>    if (Build.VERSION.SDK_INT &gt;= Build.VERSION_CODES.TIRAMISU) {<br>        this?.getParcelable(keyName, ParcelableClass::class.java)<br>    } else {<br>        @Suppress(&quot;DEPRECATION&quot;)<br>        this?.getParcelable&lt;ParcelableClass&gt;(keyName)<br>    }<br>}</pre><h4>Limitations</h4><p>If you decide to use this solution, you must know that it is not the intended way to use the Navigation library with Jetpack Compose. Because some of the code strongly depends on the specific library implementation, this approach might break if it goes through big changes under the hood. Each programmer should consider the risk and the probability of library refactoring.</p><p>One of the things that would be useful to add in the project that uses this solution is simple unit tests that could alert if the described solution stops working as intended.</p><p>In the next part, I will show how these findings can be translated into a generic solution that can be reused across multiple apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1087634b984a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/intent-based-compose-navigation-1087634b984a">Intent-Based Compose Navigation</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>