LinearLayout내에서 사용할 커스텀뷰를 만들고 있는데 리니어레이아웃 내에서
자식 커스텀뷰들을 선택 여부를 확인할 방법 추가해야하는 상황입니다. 나중에 선택여부를 확인해
선택된 커스텀뷰의 텍스트들을 꺼내어 다른곳으로 보낼 예정입니다.
아무튼 이런 상황에서 단순히 두가지 방법이 생각났는데.
1. 커스텀뷰 클래스 내에 변수를 하나 정의후 선택되었는지 안되었는지 알 수 있는 메소드 정의후 리턴한다.
2. 커스텀뷰의 attrs xml 파일내에 체크관련 새로운 속성을 정의한다
처음에는 2번으로 하려고
<resources>
<declare-styleable name="BodyPartCustomView">
<attr name="part" format="string" />
<attr name="isSelected" format="boolean" />
</declare-styleable>
</resources>
이 같은 코드를 만들었는데... format 그러니까 타입이 boolean으로 설정했음에도
커스텀뷰 내에서
var isChecked = cvAttrs.getText(R.styleable.BodyPartCustomView_isSelected)
이런식으로 불러오니 isChecked가 Boolean 타입이 아니라 CharSequence 타입이 되어 문자열 처럼 사용해야하는 것이었습니다.
이렇게되면 선택되고 안되었을때 매번 문자열로 true false를 검사해야할것같고 해서 더 복잡해질것같아서
1번방향으로 틀었는데 괜찮을까요..?
마침 isSelected라는 이름으로 메소드를 정의하려고하니 이미 View 클래스내에 정의가 되어있어 오버라이드하면 되었습니다..그래서 변수를 정의하고 선택될때마다 선택되었는지 안되었는지 판별할 생각인데 괜찮을까요?
소스는 대충
class BodyPartCustomView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyle: Int = 0): FrameLayout(context, attrs, defStyle) {
private val part: TextView by lazy { findViewById(R.id.part) }
private val img: ImageView by lazy { findViewById(R.id.state) }
var isChecked: Boolean = false
init {
LayoutInflater.from(context).inflate(R.layout.body_part_custom_view, this)
init(attrs, defStyle)
}
private fun init(attrs: AttributeSet?, defStyle: Int) {
val cvAttrs = context.obtainStyledAttributes(
attrs, R.styleable.BodyPartCustomView, defStyle, 0
)
val partValue = cvAttrs.getText(R.styleable.BodyPartCustomView_part)
part.text = partValue
this.setOnClickListener {
img.visibility =
if (img.visibility == View.INVISIBLE) {
isChecked = true
View.VISIBLE
}
else {
isChecked = false
View.INVISIBLE
}
}
}
override fun isSelected(): Boolean = isChecked
}
이러한 형식으로 될것같습니다..