From the course: Android Compose with Kotlin

Define screens with activities and composables - Kotlin Tutorial

From the course: Android Compose with Kotlin

Define screens with activities and composables

- [Instructor] You can define Android UI elements in XML or using Kotlin. Historically, XML layouts have been used to create the UI for Android applications. However, the Android team has encouraged the community to migrate to Kotlin, specifically Jetpack compose. Compose aims to simplify and accelerate user interface development on Android. It does this primarily through declarative UI. Simply put, you describe what the UI should look like for a given state, and the framework figures out how to do it. Notice the example code on the website. It describes two main states. One is where the card's text is visible and the other, it's not. From here, the Compose compiler takes care of the rest. In this course, I'll show you how to move from view-based UIs to composables to develop app screens. Let's move over to Android Studio to look at how the structure of activities differs between views and composables. First, the Compose activity. It extends the ComponentActivity class. This is what allows us to support multiple versions of Android. As part of extending this class, there are various methods that we can override, which is how we properly work with the activities lifecycle. The first is the onCreate method, which starts here on line number nine. Here we make a call to the superclass' onCreate function, and then we call the EdgeToEdge function. This method automatically declares that the app should be laid out edge to edge, and it adjusts the colors of the system bars. This is a convenience method that handles various API levels for you. Next, starting on line number 12, we use to setContent function to provide our composable layout. This is roughly equivalent to calling ComponentActivity.setContentView with a Compose view, and that's it. Now let's move over to our view-based activity. This one is named MainViewActivity, and it should be pretty familiar to you. We're extending the AppCompatActivity, which is just an extension of the ComponentActivity class. Since we're using view binding for this project, we define our binding variable here on line number 22. Then in the onCreate method, which starts on line number 30, we inflate it and pass it to the setContentView function, and then we do some setup of our UI. So far, both of our main activities have been very similar and that's intentional. In modern Android applications, there are typically only a few activity classes, if that. Compose development leans into this pattern as well.

Contents