Create Composables with Jetpack Compose

Sep 10 2024 · Kotlin 1.9, Android 14, Android Studio Jellyfish | 2023.3.1

Lesson 01: Define a Composable

Demo

Episode complete

Play next episode

Next
Transcript

Open the Starter project in the 01-define-a-composable directory of the m3-cjp-materials repo in Android Studio Jellyfish or later.

Wait for the project to be built.

As is customary with any programming tutorial introduction, you’ll start with a simple composable that displays the text Hello Compose on the screen.

Open the MainActivity.kt file.

First, let’s create our HelloCompose composable.

Enter the following snippet after the MainActivity class:

@Composable
fun HelloCompose() {
  Text(text = "Hello Compose!")
}

In the snippet above:

  • You created a composable named HelloCompose.
  • This composable invokes the Text composable and renders the message “Hello Compose.”

To see this composable on your screen, you need to use it in your activity.

Type the following after super.onCreate() in your onCreate function:

//1
setContent {
  Box( //2
    modifier = Modifier.fillMaxSize(), //3
    contentAlignment = Alignment.Center //4
  ) {
    HelloCompose() //5
  }
}

The snippet above does a few things:

  1. It uses the special setContent lambda to host composables within your activity.
  2. You then use a Box composable, which is analogous to a FrameLayout from views as your parent composable.
  3. You tell the compiler to give the box the entire available space by using the fillMaxSize() modifier.
  4. You tell the compiler to align all children to the center of the screen.
  5. You finally call the HelloCompose composable.

You’ll cover layout composables and modifiers in upcoming lessons.

Finally, add the following imports:

import androidx.compose.material.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier

After building and running the app, you should see a text in the center of your screen that says, “Hello Compose!”

Building and running is one way to view your composables. The other way is using compose previews.

Previews in compose render your composable within Android Studio in the Design view.

To preview your newly created composable, add the following method after HelloCompose:

@Preview(showBackground = true)
@Composable
fun HelloComposePreview() {
  HelloCompose()
}

With this new preview function, you should now see your composable show up in the design view of Android Studio.

That concludes this demo. Continue with the lesson for a summary.

See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Conclusion