Buttons are one of the most important UI elements for user interaction. In this Android Jetpack Compose tutorial, let’s learn how to add a button to your app.
Button composable is used to create buttons. See the code snippet given below.
Button(onClick = { println("Button Clicked!") }, modifier = Modifier.align(Alignment.Center), colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)) {
Text(text = "Button", color = Color.White)
}
This is a blue colored button with text. It prints Button Clicked! when the button is pressed. See the full code given below.
package com.example.example
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import com.example.example.ui.theme.ExampleTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ExampleTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
buttonExample()
}
}
}
}
}
@Composable
fun buttonExample() {
Box() {
Button(onClick = { println("Button Clicked!") },
modifier = Modifier.align(Alignment.Center),
colors = ButtonDefaults.buttonColors(backgroundColor = Color.Blue)) {
Text(text = "Button", color = Color.White)
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
ExampleTheme {
buttonExample()
}
}
Following is the output of the above Jetpack Compose example.

I hope this Android button tutorial will be helpful for you.