I have a Text and an Icon composable. I want the icon to stick to the right of composable. This is the code I have:
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
text = subjectName,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
textAlign = TextAlign.Center,
)
Icon(
painter = painterResource(id = R.drawable.ic_arrow_drop_down),
contentDescription = null
)
}
The corresponding UI is:
This looks fine but when the text is too long and there is an overflow, the icon gets out of the screen like this:
Instead I want to make it look like this:
I tried giving the Text
composable a weight(1f)
modifier so that the Icon is placed first. Now it looks fine with overflown text, but when text is shorter, the Icon is still placed at the end because the Text is occupying the entire remaining width:
How can I get the desired UI (image 1 & 3) here?
CodePudding user response:
Just apply the weight(1f, fill=false)
modifier to the Text
.
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.
Something like:
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
Text(
text = "subjectName",
modifier = Modifier.weight(1f, false),
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Icon(
Icons.Filled.Add,
contentDescription = "contentDescription"
)
}