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