How to define a composable function in Kotlin Android?

Define a composable function in Kotlin Android

To define a composable function in Kotlin Android, add the @Composable annotation for the function.

For example, consider the following function.

fun MessageCard(name: String) {

}

To make this MessageCard function a composable function, add the @Composable annotation as shown in the following.

@Composable
fun MessageCard(name: String) {

}

Please note that composable functions can only be called from other composable functions.

Now, you can call built-in composable functions or other user defined composable functions in this composable function.

@Composable
fun MessageCard(name: String) {
    Text("Hello Android")
}

Now, let us add this MessageCard Composable function to the UI.

Please note that the composable functions are written in Kotlin files, outside the Activity class.

For example, in the following MainActivity.kt, we have the Activity class, and then we have the user defined composable function MessageCard.

MainActivity.kt

package com.example.myapplication

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import com.example.myapplication.ui.theme.MyApplicationTheme

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                MessageCard("Android")
            }
        }
    }
}

@Composable
fun MessageCard(name: String) {
    Text("Hello $name")
}

Screenshot

This is how you can define your own Composable functions, and use them in UI.