Home > Enterprise >  How to align different elements inside a Button in Jetpack Compose?
How to align different elements inside a Button in Jetpack Compose?

Time:09-22

I am trying to build the following component,

enter image description here

Following is my code,

Button(onClick = { /*TODO*/ }, modifier = Modifier.fillMaxWidth()) {
                            Image(painter = painterResource(id = R.drawable.ic_check_circle) , contentDescription = "")
                            Text(text = "John Doe", textAlign = TextAlign.Start)
                            Image(painter = painterResource(id = R.drawable.ic_arrow_forward), contentDescription = "",
                                alignment = Alignment.TopEnd)
                    }

CodePudding user response:

You can use Spacer:

  1. Modifier.width(10.dp) will give you static size.

  2. Modifier.weight(1f)) will fill all available space.

Button(onClick = { /*TODO*/ }, modifier = Modifier.fillMaxWidth()) {
    Image(painter = painterResource(id = R.drawable.ic_undo) , contentDescription = "")
    Spacer(modifier = Modifier.width(10.dp))
    Text(text = "John Doe")
    Spacer(modifier = Modifier.weight(1f))
    Image(painter = painterResource(id = R.drawable.ic_redo), contentDescription = "")
}

Result:

CodePudding user response:

Wrap the components inside your button compose function with a Row and set the horizontalArrangement to Arrangement.SpaceBetween. See the modified version of your code snippet below.

   Button(onClick = { /*TODO*/ }, modifier = Modifier.fillMaxWidth()) {
Row(modifier = Modifier
    .align(alignment = Alignment.CenterVertically)
    .fillMaxWidth(0.9f)) {
    Image(painter = painterResource(id = R.drawable.ic_baseline_subject_24),
        contentDescription = "", alignment = Alignment.CenterStart)
    Spacer(modifier = Modifier.width(10.dp))
    Text(text = "John Doe", textAlign = TextAlign.Start, modifier = Modifier.align(alignment = Alignment.CenterVertically))
}
Image(painter = painterResource(id = R.drawable.ic_baseline_subject_24),
    contentDescription = "")

}

  • Related