How to add bulleted list to android application?

后端 未结 17 1395
抹茶落季
抹茶落季 2020-11-29 19:14

I have googled my question but there is not working answer provided. How do add a bulleted list to my textview.

17条回答
  •  鱼传尺愫
    2020-11-29 20:01

    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)
            }
        }
    }
    

提交回复
热议问题