Friday 5 April 2019

Android: Display bulleted list in a TextView

The BulletSpan class in Android has some quirks about it which makes it a little difficult to use. For example, each character sequence which is to be bulleted has to be preceded by a new line character. And using BulletSpan alone you're not able to specify how much vertical space you want between each bulleted character sequence. For this reason I've put together a Kotlin extension function on the SpannableStringBuilder class named appendBulletSpans(...) which takes the difficulty away from creating a bulleted list.

You can use this extension function as follows:

val spannableStringBuilder = SpannableStringBuilder()

spannableStringBuilder.append("Here is a list of fruits:")

    paragraphs = arrayOf("apple", "banana", "carrot"),
    putVerticalSpaceBeforeFirstParagraph = true,
    verticalSpaceToPutBetweenParagraphs = verticalSpaceInPixels,
    horizontalSpaceToPutBetweenBulletPointAndParagraph = horizontalSpaceInPixels,
    bulletPointColor = Color.BLACK

textView.text = spannableStringBuilder

This will render the text in a TextView as follows:
You can find the source code for this extension function in the SpannableStringBuilderExtensions.kt file in this repository.