I have googled my question but there is not working answer provided. How do add a bulleted list to my textview.
Ready-to-use Kotlin extension
fun List.toBulletedList(): CharSequence {
return SpannableString(this.joinToString("\n")).apply {
this@toBulletedList.foldIndexed(0) { index, acc, span ->
val end = acc + span.length + if (index != this@toBulletedList.size - 1) 1 else 0
this.setSpan(BulletSpan(16), acc, end, 0)
end
}
}
}
Usage:
val bulletedList = listOf("One", "Two", "Three").toBulletedList()
label.text = bulletedList
Colors and size:
To change bullet color or size use CustomBulletSpan instead of BulletSpan
package com.fbs.archBase.ui.spans
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.text.Layout
import android.text.Spanned
import android.text.style.LeadingMarginSpan
import androidx.annotation.ColorInt
class CustomBulletSpan(
private val bulletRadius: Int = STANDARD_BULLET_RADIUS,
private val gapWidth: Int = STANDARD_GAP_WIDTH,
@ColorInt private val circleColor: Int = STANDARD_COLOR
) : LeadingMarginSpan {
private companion object {
val STANDARD_BULLET_RADIUS = Screen.dp(2)
val STANDARD_GAP_WIDTH = Screen.dp(8)
const val STANDARD_COLOR = Color.BLACK
}
private val circlePaint = Paint().apply {
color = circleColor
style = Paint.Style.FILL
isAntiAlias = true
}
override fun getLeadingMargin(first: Boolean): Int {
return 2 * bulletRadius + gapWidth
}
override fun drawLeadingMargin(
canvas: Canvas, paint: Paint, x: Int, dir: Int,
top: Int, baseline: Int, bottom: Int,
text: CharSequence, start: Int, end: Int,
first: Boolean,
layout: Layout?
) {
if ((text as Spanned).getSpanStart(this) == start) {
val yPosition = (top + bottom) / 2f
val xPosition = (x + dir * bulletRadius).toFloat()
canvas.drawCircle(xPosition, yPosition, bulletRadius.toFloat(), circlePaint)
}
}
}