I am trying to use Compose in my app.
I want to draw a UI like below.
It has Title and Description with a Switch.
My code is here:
@Composable
fun Switch2Lines(
@StringRes title: Int,
@StringRes desc: Int
) {
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Column {
Text(
text = "Title",
modifier = Modifier.padding(top = 16.dp),
fontSize = 18.sp
)
Text(text = "Desc Desc Desc Desc Desc Desc Desc Desc Desc Desc")
}
Switch(
checked = true,
onCheckedChange = {},
modifier = Modifier.wrapContentSize()
)
Spacer(modifier = Modifier.padding(16.dp))
}
}
In this case, Description is too long.
So the Switch is laid out incorrectly.
I added a Spacer
end of the Switch, but it doesn't work.
How can I fix this? Should I use the constraintlayout-compose?
CodePudding user response:
You can remove the Spacer and instead use a weight modifier for your Column
.
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(16.dp)
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = "Title",
modifier = Modifier.padding(top = 16.dp),
fontSize = 18.sp
)
Text(text = "Desc Desc Desc Desc Desc Desc Desc Desc Desc Desc")
}
Switch(
checked = true,
onCheckedChange = {},
modifier = Modifier.wrapContentSize()
)
}
To understand how weight works you can read the documentation here
/**
* Size the element's width proportional to its [weight] relative to other weighted sibling
* elements in the [Row]. The parent will divide the horizontal space remaining after measuring
* unweighted child elements and distribute it according to this weight.
* When [fill] is true, the element will be forced to occupy the whole width allocated to it.
* Otherwise, the element is allowed to be smaller - this will result in [Row] being smaller,
* as the unused allocated width will not be redistributed to other siblings.
*
* @param weight The proportional width to give to this element, as related to the total of
* all weighted siblings. Must be positive.
* @param fill When `true`, the element will occupy the whole width allocated.
*/
@Stable
fun Modifier.weight(
/*@FloatRange(from = 0.0, fromInclusive = false)*/
weight: Float,
fill: Boolean = true
): Modifier
So it measures the unweighted children first (Switch in this case) and then divides the remaining space between the weighted chindren. Since Column is the only child here, any value of weight should work here.