Textview 中的订单列表 Android Kotlin

Order List in Textview Android Kotlin

嘿,我想在 android Kotlin 的文本视图中按顺序列表显示文本。我试过了Ordered List inside an Android Textview。我尝试了它有效的代码,但它未匹配 numbertext 的高度。我将分享我到目前为止所做的代码。

NumberIndentSpan.kt

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

class NumberIndentSpan(
    private val leadWidth: Int,
    private val gapWidth: Int,
    private val index: Int
) : LeadingMarginSpan {

    override fun getLeadingMargin(first: Boolean): Int = leadWidth + gapWidth

    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,
        layout: Layout?
    ) {
        if (first) {
            val orgStyle = p!!.style
            p.style = Paint.Style.FILL
            val width = p.measureText("4.")
            c!!.drawText("$index.", (leadWidth + x - width / 2) * dir, bottom - p.descent(), p)
            p.style = orgStyle
        }
    }
}

MainActivity.kt

 val list = mutableListOf(
                "Log in Google account\n",
                "Scroll to the page\n",
                "Tap disconnect from account to logout"
            )
            var number = 1
            val builder = SpannableStringBuilder()
            for (text in list) {
                val contentStart: Int = builder.length
                builder.append(text)
                builder.setSpan(NumberIndentSpan(15, 15, number), contentStart, builder.length, 0)
                number++
            }
            textView.text = builder

我想将 numbertext 放置在相同的高度。如图所示,我从这段代码中得到了什么。我也遇到格式问题,例如 1st point 和 2nd point 文本开始不同,我想要顺序。我该如何解决所有这些问题。提前致谢

我遇到了同样的问题。那是因为您应用了自定义字体,并且很可能在 Y 定位期间没有考虑额外的行距。

这是我的工作解决方案: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)
        }
    }
}