zhujie
2025-04-03 fe04012057d024770e0180543483d393281a542f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.example.firstapp.view
 
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
 
class UnderlineTextView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
 
    private val underlinePaint = Paint().apply {
        color = ContextCompat.getColor(context, android.R.color.black)
        strokeWidth = context.resources.displayMetrics.density * 2 // 2dp
    }
 
    private var showUnderline = false
 
    fun setUnderlineVisible(visible: Boolean) {
        showUnderline = visible
        invalidate()
    }
 
    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        
        if (showUnderline) {
            val textWidth = paint.measureText(text.toString())
            val startX = (width - textWidth) / 2
            canvas.drawLine(
                startX,
                height - underlinePaint.strokeWidth,
                startX + textWidth,
                height - underlinePaint.strokeWidth,
                underlinePaint
            )
        }
    }