如何使元素填充 Jetpack Compose 中行内的剩余空间

时间:2021-03-14 08:01:57

标签: android android-jetpack-compose

我试图连续显示两个文本消息,但是当第一个文本的大小很大时,第二个视图被推出屏幕,如下所示:

代码:

Row(modifier = Modifier.fillMaxWidth()) {
    Text(
        text = "safasfasdfsasdssdsaasdsadsdsaasdsasdsasdasddassdsssdasdadsasdasdsd",
        modifier = Modifier
            .padding(top = 12.dp, bottom = 12.dp, end = 12.dp, start = 10.dp)
            .background(Color.Gray)
    )
    Text(
        text = "12:00 am",
        style = messageTimeTextStyle,
        modifier = Modifier
            .padding(horizontal = 16.dp),
        maxLines = 1
    )
}

输出: enter image description here

2 个答案:

答案 0 :(得分:4)

您可以将weight修饰符应用于长文本。

.weight 修饰符将元素的宽度与它相对于 Row 中其他加权同级元素的权重成正比。父元素将测量未加权的子元素后划分出剩余的水平空间,并根据这个权重进行分配

类似于:

Row() {
    Text(text = "safasfasdfsasdssdsaasdsadsdsaasdsasdsasdasddassdsssdasdadsasdasdsd",
        Modifier
            .padding(top = 12.dp, bottom = 12.dp, end = 12.dp, start = 10.dp)
            .background(Color.Gray)
            .weight(1f)
         )
    Text(
        text = "12:00 am",
        modifier = Modifier
            .padding(horizontal = 16.dp),
        maxLines = 1
    )
}

enter image description here

Row() {
    Column(Modifier.weight(1f)){
        Text(text = "safasfasdfsasdssdsaasdsadsdsa.." , ....)
    }
    Column() {
        Text( text = "12.00 ..", .....)
    }
}

答案 1 :(得分:0)

如果您将文本包裹在盒子中并赋予盒子重量,那么您就会得到您想要的东西:

Row(modifier = Modifier.fillMaxWidth()) {
        Box(Modifier.weight(2f)) {
            Text(
                text = "safasfasdfsasdssdsaasdsafasfasdfsasdssdsaasdsafasfasdfsasdssdsaasd",
                Modifier
                    .padding(top = 12.dp, bottom = 12.dp, end = 12.dp, start = 10.dp)
                    .background(Color.Gray)
            )
        }
        Box(Modifier.weight(1f)) {
            Text(
                text = "12:00 am",
                modifier = Modifier
                    .padding(horizontal = 16.dp),
                maxLines = 1
            )
        }
    }