@BindingAdapter({"bind:imgRes"})
public static void imgload(ImageView imageView, int resid) {
imageView.setImageResource(resid);
}
}
TestBindingAdapter라는 클래스는 그냥 자바는 클래스 내에 코드를 적어야 하기 때문에 만들어 놓은 것이라고 생각하시면 됩니다.
그냥 마음대로 클래스 하나 생성하시구요.
중요한 부분이 imgload static 함수 입니다.
public static void 로 정의 하신 다음에 적용 하고 싶으신 View를 매개변수 첫번째에 넣습니다.
그리고 두번째 매개변수 부터는 받아오는 값을 넣습니다.
그리고 BindingAdapter annotation으로 함수를 정의 합니다.
"bind:imgRes" 가 xml 에서 "app:imgRes"로 사용할 예정 입니다.
여기서 app은 아래와 같은 xml 네임 스페이스 죠.
xmlns:app="http://schemas.android.com/apk/res-auto"
imgRes와 imgload(함수명)은 꼭 같은 필요가 없습니다. Spring을 써보신 분들은 아시겠지만, 그냥 함수명일 뿐이죠 ㅎ
로컬에서 부를 때는 저 함수를 부르면 됩니다.
이제 함수는 정의 되었으니 XML에 적용 시켜 보겠습니다.
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent" android:layout_height="match_parent">
<data>
<variable
name="data"
type="com.example.Data"/>
</data>
<ImageView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:imgRes="@{data.resid}"/>
</layout>
자 위와 같이 하면 됩니다.
아래가 중심이 되는 부분이죠.
app:imgRes="@{data.resid}"
annotation으로 정의된 이름으로 정의 한 다음에 바인딩을 시키면 됩니다.
이렇게 클래스에 static 함수를 BindingAdapter라는 annotation만 정의하면
xml에서 편하게 이미지를 부를 수도 있습니다.