Android SDK:为单词设置虚线下划线

问题描述 投票:0回答:1

我已经使用现有的ForegroundColorSpan 和BackgroundColorSpan 实现了一些跨越。现在,我需要通过下划线虚线选择一个单词。我用谷歌搜索并找到了一个例子:How do I make a dotted/dashed line in Android? 但是,他们将跨度应用于整个 TextView 而不是选择。我尝试使用layout.getSelectionPath(),但似乎我误解了此方法的工作原理,因为我没有看到要应用的跨度。
这就是我尝试实现它的方式:

class DashedUnderlineSpan(private val layout: Layout) : LineBackgroundSpan, LineHeightSpan {

    override fun chooseHeight(
        text: CharSequence, start: Int, end: Int, spanstartv: Int, v: Int,
        fm: FontMetricsInt
    ) {
        val spacingExtra = 2f
        fm.ascent = (fm.ascent - spacingExtra).toInt()
        fm.top = (fm.top - spacingExtra).toInt()
        fm.descent = (fm.descent + spacingExtra).toInt()
        fm.bottom = (fm.bottom + spacingExtra).toInt()
    }

    override fun drawBackground(
        canvas: Canvas, p: Paint, left: Int, right: Int, top: Int, baseline: Int,
        bottom: Int, text: CharSequence, start: Int, end: Int, lnum: Int
    ) {
        val paint = Paint()
        paint.color = Color.GRAY
        paint.style = Paint.Style.STROKE
        paint.setPathEffect(DashPathEffect(floatArrayOf(0f, 30f), 0f))
        paint.strokeWidth = 2f
        val path = Path()
        layout.getSelectionPath(0, 5, path)
        canvas.drawPath(path, paint)
    }
}

如何实现虚线下划线行为?

android textview spannablestring spannable android-spannable
1个回答
0
投票

类 DashedUnderlineSpan(私有 val 布局:布局) : LineBackgroundSpan, LineHeightSpan {

override fun chooseHeight(
    text: CharSequence, start: Int, end: Int, spanstartv: Int, v: Int,
    fm: FontMetricsInt
) {
    val spacingExtra = 2f
    fm.ascent = (fm.ascent - spacingExtra).toInt()
    fm.top = (fm.top - spacingExtra).toInt()
    fm.descent = (fm.descent + spacingExtra).toInt()
    fm.bottom = (fm.bottom + spacingExtra).toInt()
}

override fun drawBackground(
    canvas: Canvas, p: Paint, left: Int, right: Int, top: Int, baseline: Int,
    bottom: Int, text: CharSequence, start: Int, end: Int, lnum: Int
) {
    val paint = Paint()
    paint.color = Color.GRAY
    paint.style = Paint.Style.STROKE
    paint.setPathEffect(DashPathEffect(floatArrayOf(0f, 30f), 0f))
    paint.strokeWidth = 2f
    val path = Path()
    layout.getSelectionPath(0, 5, path)
    canvas.drawPath(path, paint)
}

}

© www.soinside.com 2019 - 2024. All rights reserved.