10th Sep 2021

Adopting Jetpack Compose with Interop API

Mobile App

Written By, Mahek Thaker

introAdopting Jetpack Compose with Interop API

Are you learning Jetpack compose but worried about migrating your current code without breaking it? Here is interoperability APIs to make your life easier

Register Service

We have mainly these three APIs for interoperability

  1. ComposeView : It is basically a view which gets declared in your traditional xml layout file & with the help of its id you can reference it as any traditional android view & write jetpack compose code directly.
  2. AbstractComposeView : It provides you the capability to make your own custom views directly into compose & later on you can include them in your xml layout file.
  3. AndroidView : it provides you the capability to use any Views which are not yet available in compose like MapView, AdvView or even your customViews in compose & start using them right away.

Code time :

So far in theory we know about these interoperability APIs, now let’s see how they are used practically in code

ComposeVIew:

As we can see here i have simply declared in my xml, Now let’s see how to write our compose code with it

Now the key thing to note here is that the setContent block for our composeChips,In that block now we can write the compose code that we want. For instance I have called my Composable function which has code for creating a Chip design & its content is displayed in composeChips.

AbstractComposeView

Here I have my class extending AbstractComposeView & created a Toolbar which has a search bar design having one trailing icon with onClickListener, along with that my two variables for searching the text & my function which will execute on the click of the trailing icon.

Now we can include this class in our xml file

So far so good, now we can reference this in the kotlin file & set up our variables for final use.

With the reference from xml we can now set up our class variables

AndroidView

We are now going to use our CustomView with compose for that i have created Compose Activity & my CustomVIew which works like EmailValidator

So this is my CustomView. I changed the attribute’s value to be an assignment from the constructor directly as we don’t have xml in Compose to pass our attributes.Now let’s add this to our Compose Activity

So here in my GetEmailValidator composable function I am using AndroidView & after passing parameters like modifiers, in the factory parameter block I am constructing my CustomEmailValidator & in the constructor I am passing necessary parameters.

Output:

output-1

output

Here is link to the repository if you want to explore the app

Conclusion

These interoperability APIs surely will come handy in your journey of Jetpack Compose & knowing these APIs will encourage you to start adapting compose in your current code base.

I hope you had a good time reading the article.

Written By,

Android Developer at Yudiz Solutions Pvt. Ltd