简体   繁体   English

Jetpack Compose 中的文本布局优先级

[英]Text layout priority in Jetpack Compose

I have two texts in a row:我连续有两个文本:

Row {
    Text(
        "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.",
        maxLines = 1,
        style = MaterialTheme.typography.h4,
        modifier = Modifier
            .background(Color.Cyan)
    )
    Spacer(
        modifier = Modifier
            .weight(1f)
            .requiredWidthIn(min = 10.dp)
    )
    Text(
        "Second",
        style = MaterialTheme.typography.h5,
        modifier = Modifier
            .requiredWidth(IntrinsicSize.Min)
            .background(Color.Yellow.copy(alpha = 0.5f))
    )
}

First one can be quite long.第一个可能很长。 When it happens, second text gets compressed and disappears from the view.当它发生时,第二个文本被压缩并从视图中消失。

requiredWidth(IntrinsicSize.Min) brings it back, but the first text is still taking all available width and goes under the second one. requiredWidth(IntrinsicSize.Min)把它带回来,但第一个文本仍然占用所有可用的宽度并进入第二个。

在此处输入图片说明

When first text is small, I need second one be at the right, that's why I use spacer between them.当第一个文本很小时,我需要第二个在右边,这就是我在它们之间使用间隔符的原因。

How can I add some layout priority to fix it?如何添加一些布局优先级来修复它?

You can add Arrangement.SpaceBetween in the Row and add the modifier weight(1f, fill= false) to the first Text :您可以在Row添加Arrangement.SpaceBetween并将修饰符weight(1f, fill= false)到第一个Text

Row(horizontalArrangement = Arrangement.SpaceBetween,
    modifier = Modifier.fillMaxWidth()) {
    Text(
        "Lorem ....",
        maxLines = 1,
        style = MaterialTheme.typography.h4,
        modifier = Modifier
            .background(Color.Cyan)
            .weight(1f, fill= false)
    )
    Text(
        "Second",
        style = MaterialTheme.typography.h5,
        modifier = Modifier
            .background(Color.Yellow.copy(alpha = 0.5f))
    )
}

在此处输入图片说明 在此处输入图片说明

You can try preventing the Text composable from filling the whole width.您可以尝试防止Text可组合填充整个宽度。

for example you can say例如你可以说

Text(text = "Lorem...", modifier = Modifier.fillMaxWidth(0.75f))

This will make the text fill its maximum width but leave 25% of remaining space for the second text.这将使文本填充其最大宽度,但为第二个文本留下 25% 的剩余空间。 of course you can change 0.75f to any value you find fit for your use case.当然,您可以将 0.75f 更改为您认为适合您的用例的任何值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM