What is the easiest way to make the width the same for all the children of a Row
in Jetpack Compose? For example, if there are 4 Box
elements within a Row
, I want each Box
to have 1/4 the width (minus the padding) of the entire row.
CodePudding user response:
You can use modifier. Row which contains max width and add weight to the box like
Modifier.fillMaxWidth().weight(1f)
For example,
Row(
modifier = Modifier.fillMaxWidth().padding(5.dp)
) {
for (i in 0..3){
Box(modifier = Modifier.fillMaxWidth().height(100.dp).weight(1f).padding(horizontal = 5.dp).background(Color.Blue))
}
}
CodePudding user response:
use the weight modifier.. Modifier.weight(1)
on all the elements
CodePudding user response:
You can use Modifier.weight(1f)
on the row's children.
A good example is these 3 Texts with different lengths.
Row(Modifier.padding(4.dp)) {
Text(
text = "boy",
modifier = Modifier
.weight(1f)
.border(width = 1.dp, Color.Blue, shape = RectangleShape)
.padding(4.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "girls",
modifier = Modifier
.weight(1f)
.border(width = 1.dp, Color.Blue, shape = RectangleShape)
.padding(4.dp)
)
Spacer(modifier = Modifier.width(4.dp))
Text(
text = "countries",
modifier = Modifier
.weight(1f)
.border(width = 1.dp, Color.Blue, shape = RectangleShape)
.padding(4.dp)
)
...}
We simply apply Modifier.weight (1F)
to make the width the same despite the different number of characters.
CodePudding user response:
Use spacedBy
attribute on Row and weight
modifier on children. Checkout the below example:
@Preview(showBackground = true)
@Composable
fun EquiRow() {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
) {
repeat(4) {
Box(
modifier = Modifier
.weight(1f)
.height(96.dp)
.background(Color.Blue)
) {
}
}
}
}