Search code examples
androidkotlintextandroid-jetpack-compose

How to find how many words are in one single line of my mobile screen in android jetpack compose


I have a very long string and I was displaying it in Text. That is multiline text I want to find how many words are in one single line.


Solution

  • You can use onTextLayout for getting all the Text related Infomation.

    Here are the steps to get the word count by line in Text.

    Explanation

    1. Get Line Count
    2. Loop through it
    3. Get Line End and extract that string
    4. Count the word from the extracted line

    Code

    @Composable
    fun Stack018() {
        val textToDraw =
            "Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups"
        
        Text(text = textToDraw,
            modifier = Modifier.fillMaxSize(),
            onTextLayout = { textLayoutResult ->
                val lineCount = textLayoutResult.lineCount
                var lineOffset = 0
                for (i in 0 until lineCount ) {
                    val lineEndIndex = textLayoutResult.getLineEnd(
                        lineIndex = i,
                        visibleEnd = true
                    )
                    val lineContent = textToDraw
                        .substring(lineOffset,lineEndIndex)
                    Log.e(TAG,"=== Word Count $i= ${lineContent.split(" ").count()}")
                    lineOffset = lineEndIndex
                }
            })
    }