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.
HelloCompose
composable.
MainActivity
class:
@Composable
fun HelloCompose() {
Text(text = "Hello Compose!")
}
In the snippet above:
-
HelloCompose
.
You created a composable named -
Text
composable and renders the message “Hello Compose.”
This composable invokes the
To see this composable on your screen, you need to use it in your activity.
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:
-
setContent
lambda to host composables within your activity.
It uses the special -
Box
composable, which is analogous to aFrameLayout
from views as your parent composable.
You then use a -
fillMaxSize()
modifier.
You tell the compiler to give the box the entire available space by using the - You tell the compiler to align all children to the center of the screen.
-
HelloCompose
composable.
You finally call the
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.
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.