[AndroidStudio] CustomText

han91·2024년 5월 8일

[AndroidStudio]

목록 보기
9/15

새로운 widget을 만들어보는 과정

우선 새로운 widget을 만들기 위해 class파일을 만들어야한다

CustomText.kt

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView

// TextView를 상속받음
class CustomText : AppCompatTextView {
    // 문자열 slicing 하는 함수
    fun process(delimeter: String) {
        // 부모 필드가 TextView라서 text를 사용할 수 있는 거임 -> 상속 받으니까
        var one = text.substring(0, 4)
        var two = text.substring(4, 6)
        // 6 이후로 나머지 다 가져오겠다는 의미
        var three = text.substring(6)

        setText("$one $delimeter $two $delimeter $three")
    }

    // 생성자 선언 => 근데 2번째 거만 쓸거임
    constructor(context: Context):super(context) {}
    // AttributeSet 까지 사용
    constructor(context: Context, attrs: AttributeSet):super(context, attrs) {
        // attrs에 CustomText 추가 & 그걸 type 이라는 변수에 담음
        val typed = context.obtainStyledAttributes(attrs, R.styleable.CustomText)
        // typed의 index를 count
        val size = typed.indexCount

        for (i in 0 until size) {
            // delimeter의 값을 가져오는 것 => index 0~size
            when (typed.getIndex(i)) {
                // CustomText_delimeter일 때만 처리
                R.styleable.CustomText_delimeter -> {
                    // CustomText의 String을 가져오고 값이 없으면 "-"를 넣어라
                    val delimeter = typed.getString(typed.getIndex(i)) ?: "-"
                    process(delimeter)
                }
            }
        }
    }
    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int):super(context, attrs, defStyleAttr) {}
}

attrs.xml -> values directory에 넣음

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--  위젯을 만드는 과정  -->
    <declare-styleable name="CustomText">
    	<!-- 새로운 attribute 추가 -->
        <attr name="delimeter" format="string"/>
    </declare-styleable>
</resources>
profile
천방지축어리둥절빙글빙글돌아가는개발자

0개의 댓글