Set Button Background Color – Android Jetpack Compose
To set background color for Button in Android Jetpack Compose, you can set the colors parameter with the required ButtonColors instance. We can create a ButtonColors instance using ButtonDefaults.buttonColors(). To this buttonColors(), specify the containerColor parameter with the required Color value.
A sample code snippet to set a Black background color for the Button composable is given below.
Button(
onClick = { },
colors = ButtonDefaults.buttonColors(
containerColor = Color.Black
)
) {
Text(text = "Click Me")
}
Example Android application with Button background color
Let us display a Button in the Android UI, using Button composable. Set the Button’s background color to Color.Black.
MainActivity.kt
package com.example.myapplication
import android.os.Bundle
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.ButtonDefaults
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
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) {
Button(
onClick = { },
colors = ButtonDefaults.buttonColors(
containerColor = Color.Black
)
) {
Text(text = "Click Me")
}
}
}
}
}
}
Screenshot
Let us play with some other background colors.
Set the Button’s background color to Blue.
Button(
onClick = { },
colors = ButtonDefaults.buttonColors(
containerColor = Color.Blue
)
) {
Text(text = "Click Me")
}
We can also set a custom RGB color using Color().
Button(
onClick = { },
colors = ButtonDefaults.buttonColors(
containerColor = Color(red = 158, green = 0, blue = 140)
)
) {
Text(text = "Click Me")
}