본문

[2017.12.04] 30. Data Binding과 Binding Adapter 개념

도입

이번 포스팅에서는 Data Binding에서 Binding Adapter의 개념과 왜 Binding Adapter를 사용하는지에 대해 정리 할 예정이다.



Binding Adpater의 개념

(출처 - https://developer.android.com/reference/android/databinding/BindingAdapter.html)

"Binding Adapter는 표현식을 갖는 값을 View에 설정하는 방법을 조작하는 메소드를 지원해준다". 사실 몇 번을 읽어도 이해가 되지 않았다. 


그래서 다른 문서를 찾아보니

(출처 - https://medium.com/google-developers/android-data-binding-custom-setters-55a25a7aea47)

"Binding Adapter는 Attribute를 커스터 마이징 할 수 있다." 고 한다.



Binding Adapter의 장점

Binding Adapter의 장점은 근본적으로 Data Binding의 장점과 일치한다. Binding Adapter를 사용하므로 "코드를 간결하게 만들어 준다."


Binding Adapter를 사용하므로

1.  View에 자주 그리고 중복적으로 사용되는 코드를 메소드화 할 수 있다. 

(예를 들어, image에 src를 설정 및 다양한 옵션을 설정 할 때 Activity에서 처리하는 것이 아니라, Binding Adapter로 Annotation를 설정 하므로 중복 코드를 제거 할 수 있다.)

1
2
3
4
5
6
@BindingAdapter("loadImage")
public static void setLoadImage(ImageView view, String path) {
    Glide.with(view.getContext())
         .load(path)
           .into(view);
}
cs


2. CustomView를 사용하지 않고 Attribute를 Custom 할 수 있다.

1
2
3
4
5
6
7
8
9
10
@BindingAdapter({"setOuterViewModel""context"})
public static <extends IModelGettable> void setViewModel(View view, ListViewModel items, Context context) {
    if (view instanceof RecyclerView) {
        OuterRecyViewAdapter<T> adapter = new OuterRecyViewAdapter<>();
        ((RecyclerView)view).setAdapter(adapter);
        ((RecyclerView)view).setLayoutManager(new LinearLayoutManager(context));
 
        adapter.setItems(items);
    }
}
cs



이해가 잘 이해되지 않았던 이유

CustomView를 많이 사용해보지 않아, Binding Adapter의 유용함을 느끼지 못했다.

그래서 CustomView를 Binding Adapter를 사용하지 않고 생성해보았다. 

CustomView를 생성해 Attribute를 Custom 하기 위해서는 

1) attr.xml 파일을 생성하고 

2) CustomView 객체 또한 생성해야 한다.

그러나 Binding Adapter를 사용하면, 이러한 수고를 줄일 수 있고 코드 가독성 또한 높아진다라는 것을 깨달았다.

(CustomView 개념 및 실습 - http://heepie.tistory.com/223)



#Data Binding #Binding Adapter #MVVM

공유

댓글