[英]How to show ellipsis (three dots) at the end of a Text line in Android Jetpack Compose?
Whether I use androidx.compose.foundation.text.BasicText or androidx.compose.material.Text , if there isn't enough space for a text it wraps to the next line, for example:无论我使用androidx.compose.foundation.text.BasicText还是androidx.compose.material.Text ,如果没有足够的空间容纳文本,它就会换行到下一行,例如:
@Composable
fun EllipsisExample() {
Box(modifier = Modifier.width(160.dp)) {
Text("Lorem ipsum dolor sit amet.")
}
}
renders:呈现:
How could I force it to be a single line and draw ellipsis at the end of it?我怎么能强制它成为单行并在它的末尾绘制省略号? The result I want in this case is something like:
在这种情况下我想要的结果是这样的:
Lorem ipsum dolor s…
Lorem ipsum dolor s…
Both BasicText and Text have overflow
and maxLines
arguments which can help you. BasicText和Text都有
overflow
和maxLines
arguments 可以帮助你。
Text(myText, maxLines = 1, overflow = TextOverflow.Ellipsis)
Here's a full single-line example:这是一个完整的单行示例:
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
)
}
}
Of course you can tune maxLines
to fit your needs:当然,您可以调整
maxLines
以满足您的需求:
Text(
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
To show three dots, you need to give definite width param your root.要显示三个点,您需要为根指定宽度参数。 In my case it is like that.
就我而言,就是这样。
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
)
}
You can set the overflow
attribute in Text
composable to TextOverflow.Ellipsis
Ex:您可以将
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
)
If you want to make the ellipsis dynamic you should use Compose's state APIs like remember
and mutableStateOf
, so any changes to state automatically update the UI如果要使省略号动态化,则应使用 Compose 的 state API,例如
remember
和mutableStateOf
,因此对 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.