Android Compose – Button onClick
Button composable has onClick parameter.
Button(
onClick = {}
)
You can assign a code block to onClick parameter.
Button(
onClick = {
Toast.makeText(
context,
"You clicked the button.",
Toast.LENGTH_LONG)
.show()
}
) {
Text(text = "Click Me")
}
When user clicks or presses on the Button, the respective onClick code executes.
Example Android application with Button onClick
Let us display a Button in the Android UI, using Button composable. We shall display a Toast, when user clicks on the button. The code to display the Toast is written inside the function for onClick parameter of Button composable.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.example.myapplication.ui.theme.MyApplicationTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyApplicationTheme {
Column(
modifier = Modifier.fillMaxWidth().padding(vertical = 20.dp),
horizontalAlignment = Alignment.CenterHorizontally) {
val context = LocalContext.current
Button(
onClick = {
Toast.makeText(
context,
"You clicked the button.",
Toast.LENGTH_LONG)
.show()
}
) {
Text(text = "Click Me")
}
}
}
}
}
}
Screenshot
Click on the Click Me button