Android Jetpack Compose:如何使文本利用完整行 space 并在溢出时将单词换行?
Android Jetpack Compose: How to make Text utilize complete row space and break the word to new line in case of overflow?
我希望文本使用完整的行 space 并在单词溢出行 space 时换行。有什么办法可以在 Jetpack Compose Text 中实现这一点?我在这里没有找到任何解决方案https://developer.android.com/jetpack/compose/text
预计:
当前:
代码:
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()
}
}
}
一个解决方案是将 space 替换为不易损坏的 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'
}
结果是:
来源here or
我希望文本使用完整的行 space 并在单词溢出行 space 时换行。有什么办法可以在 Jetpack Compose Text 中实现这一点?我在这里没有找到任何解决方案https://developer.android.com/jetpack/compose/text
预计:
当前:
代码:
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()
}
}
}
一个解决方案是将 space 替换为不易损坏的 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'
}
结果是:
来源here or