androidkotlinandroid-jetpack-composenumbered-list

How to create numbered text list in Android Jetpack Compose?


Similar to this question, given I have a List<String>, how would I create a composable function that creates a numbered/ordered and properly indented text list?

Here is what I am attempting to create:

Dialog with ordered numbered list starting with the number one


Solution

  • Using this answer as a starting point I came up with this solution.

        @Composable
        fun makeNumberedList(items: List<String>): AnnotatedString {
            var bulletNumber = 1
            val textStyle = LocalTextStyle.current
            val textMeasurer = rememberTextMeasurer()
            val bulletStringWidth = remember(textStyle, textMeasurer) {
                textMeasurer.measure(text = "$bulletNumber.\t\t", style = textStyle).size.width
            }
            val restLine = with(LocalDensity.current) { bulletStringWidth.toSp() }
            val paragraphStyle = ParagraphStyle(textIndent = TextIndent(restLine = restLine))
        
            return buildAnnotatedString {
                items.forEach { text ->
                    withStyle(style = paragraphStyle) {
                        append("${bulletNumber++}.\t\t")
                        append(text)
                    }
                }
            }
        }
    

    This is how It is used:

    listOf("Short Text", 
           "Long Text - which is a really long text field so that it'll wrap the text.",
           "This is Medium Text!")
       .let {
            Text(text = makeNumberedList(it))
        }