BindingAdapter ?
뷰의 속성을 설정하는 메서드는 여러가지가있다. TextView로 예를 들자면
text, textColor, textSize등이 있지만 내가 원하는 메서드를 만들어 사용할 수 있다.
View의 속성값을 커스터마이징 할 수 있게 해주는 bindingAdapter를 사용해보겠다.
코드는 https://ejay.tistory.com/27 에서 이어집니다.
먼저 build.gradle에 아래의 코드를 추가합니다.
plugins {
...
id 'kotlin-kapt'
}
전의 코드에서 text값을 변경과 동시에 textColor를 변경하는 코드를 작성하겠습니다.
object MainBindingAdapter {
@JvmStatic
@BindingAdapter("textChange")
fun setText(view: TextView, str: String) {
view.apply {
text = str
setTextColor(view.context.getColor(R.color.purple_700))
}
}
}
@JvmStatic : 전역변수의 Getter, Setter를 정적함수로 설정하는 어노테이션
@BindingAdapter : 괄호 안에 원하는 메소드명을 넣어주면 된다.
setText : 이 메소드명은 원하는것으로 하면 된다. (오버라이딩X)
<TextView
android:id="@+id/tv_data"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
textChange="@{vm.data.toString()}"
android:textColor="@color/black"
android:textSize="16sp" />
텍스트듀의 속성을 위와같이 하게 되면 방금 만든 textChange라는 속성을 사용할 수 있는것이고,
vm.data를 매개변수로 가지며 앞에 android:, app:를 붙이지 않아도 된다.
반응형
'Android' 카테고리의 다른 글
ADB로 APK 설치하기 (0) | 2024.12.01 |
---|---|
[Android] MVVM 패턴 (feat. DataBinding) (0) | 2022.12.12 |
[Android] 사용 중인 플러그인 (0) | 2022.12.06 |
[Android] 디자인 패턴 (0) | 2022.07.27 |