簡體   English   中英

如何在 Android Jetpack Compose 的文本行末尾顯示省略號(三個點)?

[英]How to show ellipsis (three dots) at the end of a Text line in Android Jetpack Compose?

無論我使用androidx.compose.foundation.text.BasicText還是androidx.compose.material.Text ,如果沒有足夠的空間容納文本,它就會換行到下一行,例如:

@Composable
fun EllipsisExample() {
    Box(modifier = Modifier.width(160.dp)) {
        Text("Lorem ipsum dolor sit amet.")
    }
}

呈現:

在此處輸入圖像描述

我怎么能強制它成為單行並在它的末尾繪制省略號? 在這種情況下我想要的結果是這樣的:

Lorem ipsum dolor s…

BasicTextText都有overflowmaxLines arguments 可以幫助你。

Text(myText, maxLines = 1, overflow = TextOverflow.Ellipsis)

這是一個完整的單行示例:

import androidx.compose.material.Text
import androidx.compose.ui.text.style.TextOverflow

@Composable
fun EllipsisExample() {
    Box(modifier = Modifier.width(160.dp)) {
        Text(
            text = "Lorem ipsum dolor sit amet.",
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
    }
}

在此處輸入圖像描述

當然,您可以調整maxLines以滿足您的需求:

Text(
    text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
    maxLines = 2,
    overflow = TextOverflow.Ellipsis
)

在此處輸入圖像描述

要顯示三個點,您需要為根指定寬度參數。 就我而言,就是這樣。

Column(modifier = Modifier.width(150.dp)) {
        MovieImage(
            url = movie.posterPath, modifier = Modifier
                .height(190.dp)
                .padding(8.dp)
                .clip(
                    RoundedCornerShape(CornerSize(8.dp))
                )
        )
        Text(
            text = movie.title,
            color = Color.White,
            modifier = Modifier.padding(8.dp),
            maxLines = 1,
            overflow = TextOverflow.Ellipsis
        )
}

您可以將Text composable 中的overflow屬性設置為TextOverflow.Ellipsis例如:

Text(
    text = "Compose Previews are great to check quickly how a composable layout looks like",
    maxLines = 2,
    overflow = TextOverflow.Ellipsis
)

如果要使省略號動態化,則應使用 Compose 的 state API,例如remembermutableStateOf ,因此對 state 的任何更改都會自動更新 UI

@Composable
fun MessageCard(msg: String) {
var isExpanded by remember { mutableStateOf(false) }
Text(
     text = msg,
     modifier = Modifier.padding(all = 4.dp),
     style = MaterialTheme.typography.body2,
     maxLines = if (isExpanded) Int.MAX_VALUE else 1,
     overflow = if (isExpanded) TextOverflow.Visible else TextOverflow.Ellipsis
    )
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM