DataBinding 자동객체 전환
자동 객체 전환
표현식의 userMap 객체는 값을 반환하며 이 값은 android:text 속성의 값을 설정하는 데 사용되는 setText(CharSequence) 메서드에서 볼 수 있는 매개변수 유형으로 자동으로 변환됩니다.
매개변수 유형이 불명확하면 표현식에서 반환 유형을 변환해야 합니다.
<TextView
android:text='@{userMap["lastName"]}'
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
사용자 정의 객체 전환
어떤 상황에서는 특정 유형 간에 맞춤 변환이 필요합니다. 뷰의 android:background속성에android:background속성에 Drawable이 필요하지만 지정된 color값이color 정수인 상황을 예로 들 수 있습니다. 다음 예는 Drawable이Drawable 필요한데 정수가 대신 지정된 속성을 보여줍니다
<View
android:background="@{isError ? @color/red : @color/white}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
@BindingConversion
public static ColorDrawable convertColorToDrawable(int color) {
return new ColorDrawable(color);
}
android:backgroud = "Drawable" 지정되야되는데 int 이 바인딩 표현식에서 지정됨에도 BindingConversion 정적 메서드를 이용하여 int --> Drawable로 변환하여 지정하는 것이다.
아래처럼? Drawable : int 서로 다른 타입을 지정할 순 없다. 일관되게 지정해야 된다.
<View
android:background="@{isError ? @drawable/error : @color/white}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
@BindingConversion
해당 어노테이션을 붙인 함수의 매개변수의 타입이 xml에서 속성 과 같다면 자동으로 해당 함수가 호출 된다.
예를 들어 Date를 "yy,mm.ss"와 같이 원하는 포멧의 스트링타입으로 바꿔준다.
xml 에서 text = "@{user.date}" 를 하고 그값이 Date형이면 자동으로 해당 함수가 호출된다.
다른 예로는 아래와 같이 boolean 값을 정수로 변경하여 뷰를 보여주거나 안 보여주거나 할 수 있습니다.
object ConverterUtil {
@JvmStatic
fun isZero(number: Int): Boolean = number == 0
}
/**
* The number of likes is an integer and the visibility attribute takes an integer
* (VISIBLE, GONE and INVISIBLE are 0, 4 and 8 respectively), so we use this converter.
*
* There is no need to specify that this converter should be used. [BindingConversion]s are
* applied automatically.
*/
object BindingConverters {
@BindingConversion
@JvmStatic
fun booleanToVisibility(isNotVisible: Boolean): Int {
return if (isNotVisible) View.GONE else View.VISIBLE
}
}