Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JetPack Compose Button with drawable

How can we achieve this in jetpack compose

enter image description here

I'm doing something like this

Button(
    elevation = ButtonDefaults.elevation(
        defaultElevation = 0.dp,
        pressedElevation = 8.dp,
        disabledElevation = 0.dp
    ),
    onClick = { onClick },
    shape = RoundedCornerShape(28.dp),
    modifier = modifier
        .fillMaxWidth()
        .shadow(0.dp),
    contentPadding = PaddingValues(15.dp),
    colors = ButtonDefaults.buttonColors(backgroundColor = Color.White),
    border = BorderStroke(1.dp, Color.Grey)
) {
    Box(modifier = modifier.fillMaxWidth(),
        contentAlignment = Alignment.Center) {
        Icon(
            imageVector = imageVector,
            modifier = Modifier
                .size(18.dp),
            contentDescription = "drawable icons",
            tint = Color.Unspecified
        )
        Spacer(modifier = Modifier.width(10.dp))
        Text(
            text = buttonText,
            color = Color.Black,
            textAlign = TextAlign.Center
        )
    }
}

enter image description here

So as you can see the Google logo is just left of the text I need it at the start of the box so how can I do this.

like image 883
Dheeraj Gupta Avatar asked Mar 23 '26 04:03

Dheeraj Gupta


1 Answers

As suggested in other answers you can wrap the content with a Box.
As alternative you can simply use the RowScope of the Button without any container.

Just apply a weight(1f) modifier to the Text and an offset(x=- iconWidth/2).

Something like:

Button(
   //....
) {

    Icon(
        imageVector = imageVector,
        modifier = Modifier.size(iconWidth),
        contentDescription = "drawable icons",
        tint = Color.Unspecified
    )
    Text(
        text = "Button",
        color = Color.Black,
        textAlign = TextAlign.Center,
        modifier = Modifier
            .weight(1f)
            .offset(x= -iconWidth/2) //default icon width = 24.dp
    )
}

enter image description here

If you want to use a Box, remove the contentAlignment = Alignment.Center in the Box and use:

 Box(modifier = Modifier.fillMaxWidth()) {
        Icon( /* ..... */ )
        Text(
            modifier = Modifier.fillMaxWidth(),
            text = "buttonText",
            textAlign = TextAlign.Center
        )
 }

enter image description here

like image 172
Gabriele Mariotti Avatar answered Mar 25 '26 17:03

Gabriele Mariotti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!