简体   繁体   English

Android Jetpack Compose:如何使文本利用完整的行空间并在溢出时将单词换行?

[英]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?有什么办法可以在 Jetpack Compose Text 中实现这一点? I did not find any solution here https://developer.android.com/jetpack/compose/text我在这里没有找到任何解决方案https://developer.android.com/jetpack/compose/text

Expected:预期的:

在此处输入图像描述

Current:当前的: 在此处输入图像描述

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()
            }
    
        }
    }

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:结果是:

结果

Source here or here来源在这里这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM