Pandiyan Mani
2 min readDec 7, 2021

--

How to create Gradient Button using JetPack Compose

Hi Today we look on to how to create a gradient button using JetPack Compose first we will be creating a kotlin class named GradientButton inside we will be creating a composable fun GradientButton with input parameter text in the form of string and textcolor in the form of Color and gradient in the form of Brush

Now lets look how the function look with this input

@Composable
fun GradientButton(text:String,textcolor: Color,gradient:Brush) {
}

Inside the function we will be creating a Button where we set background button default color to Transparent with the content Padding

Button(colors= ButtonDefaults.buttonColors(
backgroundColor = Color.Transparent
),onClick = {},contentPadding = PaddingValues()) {
}

Inside Button Scope we will be creating a Box with background gradient and content alignment center

Box(modifier = Modifier
.padding(horizontal = 10.dp, vertical = 8.dp)
.background(gradient),contentAlignment = Alignment.Center)
{
}

And inside Box scope will be creating a Text with text string and color for text.So the final GradientButton Function will look like

@Composable
fun GradientButton(text:String,textcolor: Color,gradient:Brush) {
Button(colors= ButtonDefaults.buttonColors(
backgroundColor = Color.Transparent
),onClick = {},contentPadding = PaddingValues()) {
Box(modifier = Modifier
.padding(horizontal = 10.dp, vertical = 8.dp)
.background(gradient),contentAlignment = Alignment.Center)
{
Text(text = text,color = textcolor)
}
}
}

And lets see how to call this from MainActivity class

class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
GradientButtonTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
GradientButton(text = "Button",
textcolor = Color.White,
gradient = Brush.horizontalGradient(colors = listOf(Purple200,Purple500)))
}
}
}
}
}

You can pass your own gradient color from UI colors

--

--