我正在尝试 Jetpack Compose,但 Row 的行为让我感到困惑。我在图标按钮旁边有一个文本,我希望图标按钮锚定到最小宽度为 48dp 的一侧,并让文本环绕它。像这样:
但是文本没有换行,它占用了行中的所有空间:
@Composable
fun SampleLayout(text: String) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text)
IconButton(
onClick = { },
) {
Icon(
imageVector = androidx.compose.material.icons.Icons.Default.StarBorder,
null
)
}
}
}
@Preview(showBackground = true, backgroundColor = 0x006EAEA0, fontScale = 1.5F)
@Composable
fun SamplePreview1() {
Box(Modifier.padding(16.dp)) {
SampleLayout("helooooo")
}
}
@Preview(showBackground = true, backgroundColor = 0x006EAEA0, fontScale = 1.5F)
@Composable
fun SamplePreview2() {
Box(Modifier.padding(16.dp)) {
SampleLayout("helooooooooooooooooooooooooooo")
}
}
@Preview(showBackground = true, backgroundColor = 0x006EAEA0, fontScale = 1.5F)
@Composable
fun SamplePreview3() {
Box(Modifier.padding(16.dp)) {
SampleLayout("heloooooooooooooooooooooooooooooooooooooooo")
}
}
我尝试将图标的最小宽度设置为 48dp,但文本仍然会填充到行尾。
如何确保文本宽度不会超过图标按钮?
Row
一个接一个地测量其子项,如果某个项目需要占用所有可用空间(例如,如果您使用 fillMaxWidth
,或者在这种情况下文本有多于一行),则下一个项目将不会有为他们留下任何空间。
如果它的布局逻辑支持压缩到零大小,那么您根本不会看到它(就像
Icon
的情况一样),否则可以在行的末尾看到它,实际上采用零大小但被绘制超出了界限。
weight
修饰符:在这种情况下,Icon
的大小将在 Text
之前计算:
父级将在测量未加权的子元素后划分剩余的垂直空间
此外,
weight
还有一个fill
参数,默认设置为true
。这相当于 fillMaxWidth
(当 weight
在 Row
内使用时),因此您可以跳过父级中的 fillMaxWidth
修饰符。当您不需要此行为时,请将 false
传递给此参数。
Row{
Text(text, modifier = Modifier.weight(1f))
IconButton(
onClick = { }
) {
Icon(
imageVector = Icons.Default.StarBorder,
null
)
}
}
试试这个
@Composable
fun SampleLayout(text: String) {
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween,
) {
Text(text = text)
IconButton(
modifier = Modifier.weight(1f, fill = false), //You must add the false fill here to keep it from occupying all the available space
onClick = { },
) {
Icon(
imageVector = androidx.compose.material.icons.Icons.Default.StarBorder,
null
)
}
}
}
您无需对
IconButton
做任何事情。尝试使用这个 Text
撰写视图:
Text(
modifier = Modifier
.weight(
weight = 1.0f,
fill = false,
),
text = text,
softWrap = false,
maxLines = 1,
)
在您的撰写功能中:
@Composable
fun YourLayout(text: String) {
Row(
modifier = Modifier,
) {
Text(
modifier = Modifier
.weight(
weight = 1.0f,
fill = false,
),
text = text,
softWrap = false,
maxLines = 1,
)
IconButton(
onClick = { },
) {
// Your content.
}
}
}