'Android Jetpack Compose: How to make Text utilize complete row space and break the word to new line in case of overflow?
I would like the text to utilize complete row space and break to a new line if the word overflows the row space. Is there any way to achieve this in Jetpack Compose Text? I did not find any solution here https://developer.android.com/jetpack/compose/text
Expected:
Code:
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MaterialTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
ShowText()
}
}
}
}
}
@Composable
fun ShowText() {
Text(text = "This is a veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerrrrryyyyyyyyyyyy looooooong text", softWrap = true)
}
@Preview
@Composable
fun Preview() {
MaterialTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colors.background
) {
ShowText()
}
}
}
Solution 1:[1]
A solution is to replace space by non breakable space :
@Composable
fun TestLongWord() {
Box(
Modifier
.fillMaxSize()
.systemBarsPadding()) {
Text(
text = "This is a veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeerrrrryyyyyyyyyyyyyyyyyyy looooooong text".useNonBreakingSpace()
)
}
}
fun String?.useNonBreakingSpace() = this.orEmpty()
.replace(
Constants.REGULAR_SPACE_CHARACTER,
Constants.NON_BREAKABLE_SPACE_UNICODE
)
object Constants {
const val REGULAR_SPACE_CHARACTER = ' '
const val NON_BREAKABLE_SPACE_UNICODE = '\u00A0'
}
The result is :
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 | Abhimanyu |