0
0
Android-kotlinHow-ToBeginner ยท 3 min read

How to Create a Composable Function in Android with Jetpack Compose

In Android, you create a composable function by annotating a Kotlin function with @Composable. This function builds UI elements declaratively and can be reused inside other composables to create flexible interfaces.
๐Ÿ“

Syntax

A composable function is a Kotlin function marked with the @Composable annotation. It returns Unit and describes UI elements declaratively.

  • @Composable: Marks the function as composable so Compose can manage its UI.
  • Function name: Should be descriptive of the UI it builds.
  • Parameters: Optional inputs to customize the UI.
  • Body: Contains Compose UI elements like Text, Button, or layout containers.
kotlin
@Composable
fun Greeting(name: String) {
  Text(text = "Hello, $name!")
}
Output
Displays a text label: Hello, [name]!
๐Ÿ’ป

Example

This example shows a simple composable function that displays a greeting message. It demonstrates how to pass parameters and use Compose UI elements.

kotlin
import androidx.compose.material.Text
import androidx.compose.runtime.Composable

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

// Usage inside another composable
@Composable
fun GreetingScreen() {
  Greeting(name = "Android Learner")
}
Output
UI shows the text: Hello, Android Learner!
โš ๏ธ

Common Pitfalls

  • Forgetting the @Composable annotation causes the function not to be recognized as a composable.
  • Trying to return UI elements directly from the function instead of using Compose's declarative style.
  • Using side effects or mutable state inside composables without proper state management.
  • Calling composable functions from non-composable code without proper context.
kotlin
/* Wrong: Missing @Composable annotation */
fun WrongGreeting(name: String) {
  Text(text = "Hello, $name!") // Error: Text can only be called from a @Composable function
}

/* Right: Add @Composable annotation */
@Composable
fun CorrectGreeting(name: String) {
  Text(text = "Hello, $name!")
}
๐Ÿ“Š

Quick Reference

Remember these key points when creating composable functions:

  • Always annotate with @Composable.
  • Use declarative UI elements inside the function.
  • Keep functions short and focused on one UI piece.
  • Pass parameters to customize UI dynamically.
  • Call composables only from other composables or Compose-aware scopes.
โœ…

Key Takeaways

Mark Kotlin functions with @Composable to create composable functions in Android.
Composable functions describe UI declaratively and can accept parameters for customization.
Always call composable functions from other composables or Compose contexts.
Avoid side effects inside composables without proper state handling.
Keep composable functions focused and reusable for better UI structure.