안드로이드 커스텀 Attribute 선언하고 Selector에 사용하기

Donggi Hong·2024년 1월 4일
1

sel_edittext.xml

<selector xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto">
    <item app:state_error="true" android:drawable="@drawable/rect_edittext_error"></item>
    <item android:drawable="@drawable/rect_edittext"></item>
</selector>

rect_edittext.xml / rect_edittext_error.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle" >
    <solid android:color="white" />
    <corners android:radius="5dp"/>
    <stroke android:width="1dp" android:color="green"/>
</shape>

여기서 stroke를 green/red 등으로 차이를 줘서 rect_edittext_error.xml 파일 생성

EditStateEditText.kt

import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import androidx.core.content.withStyledAttributes
import kr.danal.app.damoum.R
class ErrorStateEditText @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = android.R.attr.editTextStyle
) : AppCompatEditText(context, attrs, defStyleAttr) {
    companion object {
        private val ERROR_STATE_SET = intArrayOf(R.attr.state_error)
    }
    init {
        context.withStyledAttributes(attrs, R.styleable.ErrorStateEditText, defStyleAttr) {
            isError = getBoolean(R.styleable.ErrorStateEditText_state_error, false)
        }
    }
    override fun onCreateDrawableState(extraSpace: Int): IntArray {
        val drawableState = super.onCreateDrawableState(extraSpace + 1)
        if (isError) {
            mergeDrawableStates(drawableState, ERROR_STATE_SET)
        }
        return drawableState
    }
    fun setCustomErrorState(errorState: Boolean) {
        isError = errorState
    }
    var isError: Boolean = false
        set(value) {
            if (field == value) return
            field = value
            refreshDrawableState()
        }
}

BindingAdapters.kt

    @BindingAdapter("state_error")
    @JvmStatic
    fun setStateError(edittext: ErrorStateEditText, boolean: Boolean) {
        edittext.setCustomErrorState(boolean)
    }

values/attrs.xml

    <declare-styleable name="ErrorStateEditText">
        <attr name="state_error" format="boolean" />
    </declare-styleable>

layout.xml

    <myapp.ErrorStateEditText
        android:text=""
        app:state_error="@{vm.errorState ? true : false}"
        />
profile
꿈 많은 응애 안드로이드 개발자

1개의 댓글

응흐에!

답글 달기