A Journey of Migrating to Android Jetpack Compose Part II

默考文
3 min readMar 21, 2021

In A Journey of Migrating to Android Jetpack Compose Part I, I wrote down the steps of how I setup an existing Android project with Jetpack Compose UI framework.

Now I am going to put down the key things that I learnt when rewriting the Settings Screen.

Content in this article:

  • Jetpack Compose works within Fragment
  • Separate User Interactions implementation out from Composable components
  • GPU overdraw

Jetpack Compose within Fragment

Since the whole app is still structured by using Bottom Navigation with several Fragments. I want to keep this architecture until we migrate all the screens to Jetpack Compose successfully.

So the first thing that I need to do is: make Compose working within a Fragment and AppCompatActivity.

OK, then…use ComposeView…instead of a traditional xml layout.

App crashed after I made this change.

That’s because the old version of Fragment and Activity do not work with Composable components.

It works after I made the version upgrade for both Fragment and AppCompat.

Today is 21/3/2021, Android world is moving very fast as you know, the versions and solutions can be quite different in another day.

Separate User Interactions implementation out from Composable components

There are 3 different items in Settings screen, each item takes user to different places. For things like Settings screen, you always want to have a scalable solution supporting either 3 items or 20 items. And also, you don’t want to have user interaction implementation code inside of the View building class.

@Preview in Android Studio

So…I defined an Enum class holding item TITLE and DESCRIPTION, besides that I used an EnumMap mapping each item to it’s interaction Unit function. In this case, we can loop the Enum values to build the item.

And then I inject the interactions to Settings items building function. You can see there is ZERO user interaction implementation code in UI class from code below.

Clean and easy to test.

No GPU overdraw

At the end, let’s have a look at the view performance.

Just as we expected, Compose draw the UI on screen directly, there no view hierarchy underneath. GPU overdraw is not observed in Settings screen, while the bottom navigation seems having an GPU overdraw, hope we can improve that after.

Summary

Till now I really like Jetpack Compose. The way we build UI components seems very straight forward and easy to understand. I guess that’s one of the reasons why people are moving to Declarative UI development in all the platforms.

The next thing will be rebuild the Flower Screen. To be continued.

If you have not download Love Animal app, try it out 👇

Love Animal — Animal Crossing New Horizons companion app

--

--