In Jetpack Compose, we can create functions to create any type of UI element. Suppose, we create a function to create a Button, we can use it multiple times to create multiple buttons. While creating multiple Buttons, we can add functionality to them to perform any given task, which we call On-Click Event. So in this article, we will show you how you could create such a function and pass an On-Click Event to another Function in Android using Jetpack Compose. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in the Android Studio, please refer to How to Create a new Project in Android Studio with Jetpack Compose.
Step 2: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Comments are added inside the code to understand the code in more detail.
In this we will creating a custom Button Composable and pass it in out main composable.
MainActivity.kt:
package com.geeksforgeeks.demo
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.*
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
SampleScreen()
}
}
}
@Composable
fun SampleScreen() {
// save initial state
val counter = remember { mutableIntStateOf(0) }
Column(
Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(text = counter.intValue.toString(), fontSize = 50.sp)
Spacer(modifier = Modifier.height(50.dp))
// increase counter by 5
CreateButton(text = "Add 5") {
counter.value += 5
}
Spacer(modifier = Modifier.height(50.dp))
// increase counter by 10
CreateButton(text = "Add 10") {
counter.value += 10
}
Spacer(modifier = Modifier.height(50.dp))
// decrease counter by 5
CreateButton(text = "Subtract 5") {
counter.value -= 5
}
}
}
// composable function for a button
@Composable
fun CreateButton(text: String, onClick: () -> Unit) {
Button(
onClick = onClick,
colors = ButtonDefaults.buttonColors(Color.Green)
) {
Text(text = text, color = Color.White)
}
}