In Jetpack Compose, Composable functions are the fundamental building blocks of your user interface. Instead of defining layouts in XML, you create reusable Kotlin functions that describe what your UI should look like for a given state. Compose then automatically updates (recomposes) your UI whenever the data changes.
A composable function is a regular Kotlin function annotated with
@Composable. This annotation tells the Compose compiler that the function
contributes UI to your application.
@Composable
fun Greeting(name: String) {
Text(text = "Hello, $name!")
}
The above function describes what to display β not how to display it. Compose takes care of rendering it efficiently based on the app state.
@Composable Annotation
The @Composable annotation works like a bridge between your logic and the
Compose runtime. It enables special capabilities such as:
Composable functions can take parameters to make them flexible and reusable. You can pass text, images, colors, or even other composables as arguments.
@Composable
fun WelcomeCard(username: String, modifier: Modifier = Modifier) {
Column(
modifier = modifier
.padding(16.dp)
.background(Color.LightGray)
) {
Text(text = "Welcome, $username!", style = MaterialTheme.typography.titleMedium)
Text(text = "Let's explore Jetpack Compose π")
}
}
Notice how Modifier is passed as a parameter β this is a common pattern in
Compose that allows flexible styling and layout behavior.
Composable functions can call other composables to create complex UIs through composition.
@Composable
fun UserProfile() {
Column(modifier = Modifier.padding(24.dp)) {
ProfilePicture()
Spacer(modifier = Modifier.height(12.dp))
UserDetails(name = "Talha Abbas", title = "Android Developer")
}
}
@Composable
fun ProfilePicture() {
Box(
modifier = Modifier
.size(80.dp)
.clip(CircleShape)
.background(Color.Gray)
)
}
@Composable
fun UserDetails(name: String, title: String) {
Column {
Text(text = name, style = MaterialTheme.typography.titleMedium)
Text(text = title, style = MaterialTheme.typography.bodyMedium)
}
}
This composition model promotes reusability β small building blocks combine into larger UIs naturally.
You can preview your composables directly in Android Studio without running
the app on a device. Use the @Preview annotation for this:
@Preview(showBackground = true)
@Composable
fun WelcomeCardPreview() {
WelcomeCard(username = "Talha")
}
The @Preview annotation renders the composable in the IDEβs preview panel.
You can also specify parameters like showSystemUi or backgroundColor
for more realistic previews.
Modifier for layout and styling instead of parameters like padding or background.@Composable annotation (causes compile errors).Now that you understand the basics of Composable functions, the next article will dive into the Recomposition & Lifecycle β how Compose automatically updates your UI in response to data changes.