'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:
@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…
Solution 1:[1]
Both BasicText and Text have overflow
and maxLines
arguments which can help you.
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:
Text(
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.",
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Solution 2:[2]
You can set the overflow
attribute in Text
composable to TextOverflow.Ellipsis
Ex:
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
@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
)
}
Solution 3:[3]
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
)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | MohamedHarmoush |
Solution 3 | Enes Zor |