Edhar Khimich
Edhar Khimich

Reputation: 1664

How to keep specific word groups on separate lines in a Jetpack Compose text widget?

I'm working on a UI project using Jetpack Compose, and I have a requirement for a text widget. I need to ensure that specific words stay together in separate lines. For example, if the text is "Some text example for stackoverflow question," and the word 'question' appears in the second line, I want the word 'stackoverflow' to also be in the second line.

Desired output:

Some text example for
stackoverflow question

I'm looking for guidance, code examples, or best practices on how to implement this behavior in Jetpack Compose. Any suggestions on how to achieve this requirement would be greatly appreciated.

Upvotes: 0

Views: 190

Answers (1)

RandomLonelyDev
RandomLonelyDev

Reputation: 317

here is a function that should solve this issue:

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

Upvotes: 0

Related Questions