Freelancing for Pale Blue

Looking for flexible work opportunities that fit your schedule?


Primer to integrate Android Views in Jetpack Compose

Android Jul 21, 2023

Jetpack Compose is a great tool for creating user interfaces (UI) in your app. It makes the process of building views more enjoyable. However, traditional Android views have been used for the past 10 years. So, if you're developing a reasonably sized app, you might come across some older widgets that you want to use in your new shiny app built with Compose.

No worries though! The Compose team has come up with a solution—a backward-compatible API that allows you to use Android Views in your Compose app in a relatively easy and elegant way. This means you can integrate those older widgets seamlessly into your new Compose-based app.

This is a super quick primer into the basic usage of the Android Views compatibility API that can be used in Compose apps to use a "legacy" Android View widghet.

    AndroidView( // 1.
        factory = { context -> // 2.
        
            val linearLayout = LinearLayout(context).apply {
                orientation = LinearLayout.VERTICAL
            }
            val view = TextView(context).apply {
                tag = "my_view"
            }
            linearLayout.addView(view)
            linearLayout
            
        },
        update = { viewCreatedFromFactory -> // 3.
        
            val myView =
                viewCreatedFromFactory
                    .findViewWithTag<TextView>("my_view") // 4.
            [...]
            
        },
    )
  1. The compatibility layer is implemented with the AndroidView composable function.
  2. First, you need to create or inflate the Android View using the factory method. You are provided with the Android Context. For example, you can manually create a LinearLayout and add a TextView inside it.
  3. The update method is called on every recompose. This can be used to update the view element after is has been created. Remember that since this is called for every recompose, you would need to use a remember or keep track on what this update method has "consumed" in your ViewModel.
  4. You can use any method you want here to obtain references to views. Notice that the update method provides the parent view that has been created in the factory method above.

And that's it! You've learned the basics of embedding your existing Android Views into your Compose app. If you want more in-depth information, check out the excellent documentation on the official website. Happy coding!

Happy coding!

 

Tags

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.