I’ve already implemented some spanning using existing ForegroundColorSpan and BackgroundColorSpan. Now, I need to select a word via dashed underline. I googled it up and found an example: How do I make a dotted/dashed line in Android?
However, they apply the span to a whole TextView instead of a selection. I tried to use layout.getSelectionPath() and it seems I misunderstood how this method works since I don’t see the span to be applied.
This is how I tried to implement it:
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)
}
}
How can I implement the dashed underline behavior?