Instruction

Anatomy of a Composable Function

When building UIs in Compose, you define the UI using functions annotated with the @Composable annotation.

@Composable
fun HelloCompose(name: String) {
  Text(text = "Hello $name!")
}
  • All Composable functions must have this annotation.
  • The function annotated with the @Composable annotation tells the Compose compiler that this function intends to convert data into UI.
  • Just like regular functions, a Composable function can also accept parameters that can be used to describe the UI.
  • In the example above, the function takes a String parameter called ‘name’ and uses it to render a text in the UI by calling the Text() composable function, which in turn emits the UI.
  • Usually, composable functions don’t return anything. They accept parameters and use them to describe the UI.
  • Composable functions conventionally use the Pascal case naming convention.

The description above can be a blueprint for defining all Composable functions.

Previewing Composables

Jetpack Compose ships with previews, a handy feature that lets you get a sense of what your UI will look like inside Android Studio without needing to deploy your app to a running device or emulator.

In some sense, it’s similar to the design view available for XML layouts and views. Unlike the XML Design view, where the previews are limited and often inaccurate, previews for composables are a 1:1 representation of what your code will look like when deployed on the device. You also get live updates to the preview as you edit your code.

To preview a composable, you need to create another composable annotated with the @Preview annotation that calls your composable.

@Composable
fun HelloCompose(name: String) {
  Text(text = "Hello $name!")
}

@Preview  
@Composable  
fun HelloComposePreview() { 
  SimpleComposable("Steve")  
}

The @Preview annotation tells the compose compiler that you need to render this composable in Android Studio’s design view.

Previews in compose come with properties that let you customize the rendered preview. You can even add the @Preview annotation to the same function multiple times to preview a composable with different properties.

@Composable
fun HelloCompose(name: String) {
  Text(text = "Hello $name!")
}

@Preview(uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview(uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable  
fun HelloComposePreview() { 
  SimpleComposable("Steve")  
}

The snippet above renders two previews of the same composable - one in dark mode and the other in light mode.

See forum comments
Download course materials from Github
Previous: Introduction Next: Demo