撰写:在行布局中包装文本,而不是将兄弟姐妹推出

Compose: wrap text in Row layout, instead of pushing siblings out

我正在尝试 Jetpack Compose,但我对 Row 的行为感到困惑。我在图标按钮旁边有一个文本,我希望将图标按钮锚定到最小宽度为 48dp 的一侧,并在其周围环绕文本。像这样:

但是文本没有换行,它吃掉了行中的所有 space:

@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,但文本仍然会填充到行尾。

如何确保文本宽度不超过图标按钮?

默认情况下 Text 的布局优先级高于 Icon,以便填充必要的 space。您可以使用 weight 修饰符更改它。

使用该修饰符后,Icon的大小会在Text之前计算:

The parent will divide the vertical space remaining after measuring unweighted child elements

另外weight有一个fill参数,默认设置为true。这等同于 fillMaxWidth(当 weightRow 中使用时),因此您可以跳过父项中的 fillMaxWidth 修饰符。当您不需要此行为时,将 false 传递给此参数。

Row(
    horizontalArrangement = Arrangement.SpaceBetween,
) {
    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
                            )
                        }
                    }
}