android 如何在Jetpack撰写文本小部件中将特定的单词组放在单独的行上?

4c8rllxm  于 2023-06-04  发布在  Android
关注(0)|答案(1)|浏览(105)

我正在使用JetpackCompose做一个UI项目,我需要一个文本小部件。我需要确保特定的单词在单独的行中保持在一起。例如,如果文本是“Some text example for stackoverflow question”,并且单词“question”出现在第二行,我希望单词“stackoverflow”也出现在第二行。
所需输出:

Some text example for
stackoverflow question

我正在寻找关于如何在Jetpack Compose中实现此行为的指导、代码示例或最佳实践。如能就如何达到这一要求提出任何建议,将不胜感激。

oprakyz7

oprakyz71#

这里有一个函数可以解决这个问题:

fun parseText(str: String, len: Int) {
    var lineChars = 0 //total chars in a line
    val out = ArrayList<String>() //our intermediate result
    val wordArray = str.split(Regex("\\s")) //split the string on whitespace
    for(word in wordArray) {
        out.add(word)
        lineChars += (word.length + 1) //count the word's chars (plus a space) to lineChars
        if((len until len + 10).contains(lineChars)) { //if we've reached our desired line length
            out.add("\n") //add a newline
            lineChars = 0 //reset the char count for a new line
        }
    }
    val indexOfBreak = wordArray.lastIndexOf("\n") 
    if(indexOfBreak > out.size - 3 && longString.length > len) { //if a newline is one of the last two elements
        out[indexOfBreak] = out[indexOfBreak - 1] //swap the newline and the element before it
        out[indexOfBreak - 1] = "\n"
    }
    return out.joinToString(" ").split("\n ").joinToString("\n") //return the formatted string

相关问题