[Kotlin] LinedTextView

장똑대·2021년 6월 23일

📌 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 를 사용자 임의로 설정
profile
장똑대와 안드로이드

0개의 댓글