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

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

00:10Wait for the project to be built.

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

00:21Open the MainActivity.kt file.

00:25First, let’s create our HelloCompose composable.

00:28Enter the following snippet after the MainActivity class:

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

00:36In the snippet above:

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

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

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

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

01:07The snippet above does a few things:

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

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

00:28Finally, add the following imports:

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

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

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

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

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

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

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

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

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