Ordered lists inside an Android TextView

Viewed 22884

I want to display an ordered list inside a TextView, for example:
1) item 1
2) item 2

Using the following layout:

<TextView
    android:text="<ol><li>item 1\n</li><li>item 2\n</li></ol>
    />

I get:

  • item 1
  • item 2

How can I change the bullets to numbers?

Thanks.

8 Answers

I followed the answer by answer by @jk2K and made modifications to his code. As I need to have indentation for each bullet points,

String[] textArray = {
    "dfsdljjlfsdsdfjsdjldssdfidfsjdljasdfjfds\n",
    "sdfjdfjlkfdjdfkfjiwejojodljfldsjodsjfsdjdlf\n",
    "djsdfjsdffjdflljfjsadfdjfldfjl"
};

SpannableStringBuilder content = new SpannableStringBuilder();
int number = 1;
for (String t1 : textArray) {
    int contentStart = content.length();

    content.append(t1);

    int contentEnd = content.length();
    content.setSpan(
            new BulletSpan(10),
            contentStart,
            contentEnd,
            Spannable.SPAN_INCLUSIVE_EXCLUSIVE
    );

    number++;
}

I used the BulletSpan class from android library and replaced new LeadingMarginSpan.Standard(0, 66) with new BulletSpan(10) which creates a BulletSpan with width. As mentioned in the BulletSpan class documentation

BulletSpan(int gapWidth)

Creates a BulletSpan based on a gap width 

So you won't need anymore to append the bullet which is mentioned in the answer by @jk2K,

 String leadingString = number + ". ";
 content.append(leadingString);

This class handles numbering in TextView and EditText and scales the number depending on the size of the text:

import android.graphics.Canvas
import android.graphics.Paint
import android.text.Layout
import android.text.Spanned
import android.text.style.AbsoluteSizeSpan
import android.text.style.LeadingMarginSpan

/**
 * Paragraph numbering.
 *
 *
 * Android seems to add the leading margin for an empty paragraph to the previous paragraph
 * (]0, 4][4, 4] --> the leading margin of the second span is added to the ]0, 4] paragraph
 * regardless of the Spanned.flags) --> therefore we ignore the leading margin for the last,
 * empty paragraph unless it's the only one
 */
class NumberSpan(nr: Int, gapWidth: Int, isEmpty: Boolean, isFirst: Boolean, isLast: Boolean)
    : LeadingMarginSpan {

    private val mNr: Int = nr
    private val mGapWidth: Int = gapWidth
    private val mIgnoreSpan: Boolean = isEmpty && isLast && !isFirst

    private var mWidth: Float = 0.toFloat()

    val value: Boolean?
        get() = java.lang.Boolean.TRUE

    override fun getLeadingMargin(first: Boolean): Int {
        return if (mIgnoreSpan) 0 else Math.max(Math.round(mWidth + 2), mGapWidth)
    }

    override fun drawLeadingMargin(c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int,
                                   text: CharSequence, start: Int, end: Int, first: Boolean, l: Layout) {

        val spanned = text as Spanned
        if (!mIgnoreSpan && spanned.getSpanStart(this) == start) {
            // set paint
            val oldStyle = p.style
            val oldTextSize = p.textSize
            p.style = Paint.Style.FILL
            val textSize = determineTextSize(spanned, start, end, oldTextSize)
            p.textSize = textSize
            mWidth = p.measureText(mNr.toString() + ".")

            // draw the number
            c.drawText(mNr.toString() + ".", x.toFloat(), baseline.toFloat(), p)

            // restore paint
            p.style = oldStyle
            p.textSize = oldTextSize
        }
    }

    private fun determineTextSize(spanned: Spanned, start: Int, end: Int, defaultTextSize: Float): Float {
        // If the text size is different from default use that to determine the indicator size
        // That is determined by finding the first visible character within the list item span
        // and checking its size
        val position = firstVisibleCharIndex(spanned, start, end)
        if (position >= 0) {
            val absoluteSizeSpans = spanned.getSpans(position, position, AbsoluteSizeSpan::class.java)
            if (absoluteSizeSpans.isNotEmpty()) {
                val absoluteSizeSpan = absoluteSizeSpans[absoluteSizeSpans.size - 1]
                return absoluteSizeSpan.size.toFloat()
            }
        }

        // If there are no spans or no visible characters yet use the default calculation
        return defaultTextSize
    }

    private fun firstVisibleCharIndex(spanned: Spanned, start: Int, end: Int): Int {
        var newStart = start
        while (newStart < end) {
            if (isVisibleChar(spanned[newStart])) {
                return newStart
            }
            newStart++
        }

        return -1
    }

    private fun isVisibleChar(c: Char): Boolean {
        return when (c) {
            '\u200B', '\uFFEF' -> false
            else -> true
        }
    }

}

The code is from this library https://github.com/1gravity/Android-RTEditor (translated from Java to Kotlin). I'm the author of that library.

Following @Håvard answer and facing the same issue that @Vivek modi had, I implemented the next working solution which accounts for custom fonts + line spacing extras and is written in Kotlin:

https://gist.github.com/marcelpallares/ae6285ee0dcb3f04493991dcb18d01bd

class NumberIndentSpan(
    private val number: Int,
    private val leadWidth: Int = 15,
    private val gapWidth: Int = 30,
) : LeadingMarginSpan {
    override fun getLeadingMargin(first: Boolean): Int {
        return leadWidth + gapWidth
    }

    override fun drawLeadingMargin(
        canvas: Canvas,
        paint: Paint,
        x: Int,
        dir: Int,
        top: Int,
        baseline: Int,
        bottom: Int,
        t: CharSequence?,
        start: Int,
        end: Int,
        first: Boolean,
        layout: Layout?
    ) {
        if (first) {
            val text = "$number."
            val width = paint.measureText(text)

            val yPosition = baseline.toFloat()
            val xPosition = (leadWidth + x - width / 2) * dir

            canvas.drawText(text, xPosition, yPosition, paint)
        }
    }
}

I also added an extension method to use it:

fun TextView.setNumberedText(list: List<String>) {
    val content = SpannableStringBuilder()
    val gap = context.resources.getDimensionPixelSize(R.dimen.margin_16)

    list.forEachIndexed { index, text ->
        val contentStart = content.length
        content.appendLine(text)
        content.setSpan(NumberIndentSpan(index + 1, gapWidth = gap), contentStart, content.length, 0)
    }

    text = content
}

And finally a custom TextView to be able to use this from XML layouts

class OrderedListTextView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : AppCompatTextView(context, attrs) {

    init {
        setNumberedText(text.lines())
    }
}
Related