排版:文本在行布局中换行,而不是将同级排版推出 [英] Compose: wrap text in Row layout, instead of pushing siblings out

查看:20
本文介绍了排版:文本在行布局中换行,而不是将同级排版推出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试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的最小宽度,但文本仍会填充到行尾。

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

推荐答案

默认情况下TextIcon具有更高的布局优先级,以填充必要的空间。您可以使用weight修饰符更改此设置。

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

父级将划分测量未加权子元素后剩余的垂直空间

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
        )
    }
}

这篇关于排版:文本在行布局中换行,而不是将同级排版推出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆