[Kotlin] LinedTextView


📌 Result



📄 LinedTextView.kt

class LinedEditText(context: Context, attrs: AttributeSet?) :
    androidx.appcompat.widget.AppCompatEditText(context, attrs) {
    private val mRect: Rect = Rect()
    private val mPaint: Paint = Paint().apply{
        style = Paint.Style.STROKE
        strokeWidth = 3F
        color = ContextCompat.getColor(context, R.color.profile_line_color)
    }

    override fun onDraw(canvas: Canvas) {
        var curHeight = 0
        val r = mRect
        val paint = mPaint
        val baseline = getLineBounds(0, r)
        curHeight = baseline + 15 //y축과 간격 조절
        while (curHeight < height) {
            canvas.drawLine(r.left.toFloat(), curHeight.toFloat(),
                r.right.toFloat(), curHeight.toFloat(), paint)
            curHeight += lineHeight
        } //drawLine(시작점 x좌표, 시작점 y좌표, 도착점 x좌표, 도착점 y좌표)
        super.onDraw(canvas)
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        invalidate()
    }
}

📄 activity_main.xml

<com.example.test.LinedTextView
        android:layout_width="220dp"
        android:layout_height="100dp"
        android:gravity="center_horizontal"
        android:lineSpacingExtra="5dp"
        android:text="안녕하세요 \n똑대의 블로그에 오신걸 환영합니다 \n 반가워요 "
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        />
  • heightをwrap contentsとし、最後の行が見えないためレイアウト高さをdpとして指定します.
  • 行の間隔を広げる場合は、lineSpacingExtraを
  • に任意に設定できます.