brunch

You can make anything
by writing

C.S.Lewis

by 이승현 Jun 19. 2017

Butter Knife

Binding for Android

Butter Knife



Annotate fields with @BindView and a view ID for Butter Knife to find and automatically cast the corresponding view in your layout.


Butter Knife는 Annotation을 이용해 안드로이드 컴포넌트에 View를 주입하는 가벼운 라이브러리입니다.





Boilderplate code


아래 코드는 안드로이드에서 기본으로 제공하는 방법으로 작성한 Activity입니다.

EditText와 Button 같은 여러 View들을 선언하고 onCreate에서 "findViewById"를 통해 정의했습니다.

그리고 내부 익명 클래스를 통해 "ClickListener"도 설정했습니다.

String name 같은 Resource는 "getString(id)"를 통해 값을 조회했습니다.


안드로이드에서 View와 Resource는 구현법이 간단하지만 필요 이상으로 많은 코드를 작성해야 하는 단점이 있습니다. 이러한 단점(Boilerplate code)을 해소하고자 Butter Knife를 이용할 수 있습니다.


#01 Android native codes.




Butter Knife code


#01 Android codes with Butter knife.




build.gradle


dependencies {
    ...
    // Butter knife
    // https://github.com/JakeWharton/butterknife
    compile 'com.jakewharton:butterknife:8.6.0'
    annotationProcessor 'com.jakewharton:butterknife-compiler:8.6.0'
}




#01 VIEW BINDING

@BindView를 사용하여 findViewById 호출을 제거.


@BindView와 Butter Knife의 view ID로 주석을 달아 레이아웃에서 해당 뷰를 찾아 자동 캐스팅합니다.

...

//    EditText editText1
@BindView(R.id.edittext1) EditText editText1;

...

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //    editText1 = (EditText) findViewById(R.id.edittext1);
    ButterKnife.bind(this);
}




#02 RESOURCE BINDING

Resource annotation를 이용하여 Resource 조회 제거.


@BindBool, @BindColor, @BindDimen, @BindDrawable, @BindInt, @BindString으로 Resouce를 Bind 합니다.

...

//    String name
@BindString(R.string.app_name) String name;
@BindDrawable(R.drawable.graphic) Drawable graphic;
@BindColor(R.color.red) int red;
@BindDimen(R.dimen.spacer) Float spacer;

...

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //    name = getString(R.string.app_name)
    ButterKnife.bind(this);
}




#03 LISTENER BINDING

@OnClick 및 기타 메서드에 주석을 달아 익명의 내부 클래스를 제거.


...

//    View.OnClickListener onClickListener = new View.OnClickListener() {
//        @Override
//        public void onClick(View v) {
//            // Click a button
//        }
//    };

@OnClick(R.id.button) void submit() {
    // Click a button
}

@OnClick(R.id.submit) void submit(Button button) {
    // Click a button
}

@OnClick({R.id.button, R.id.edittext1, R.id.edittext2})
void submit(View view) {
    switch (view.getId()) {
        case R.id.button:
            break;
        case R.id.edittext1:
            break;
        case R.id.edittext2:
            break;
    }
}

...

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ButterKnife.bind(this);
}








Butter Knife를 이용하면 View와 Resouce를 이용하기에 코드 작성이 간단해지고 가독성도 높아지는 장점이 있습니다.

하지만 View나 Resouce를 private로 선언하지 못한다는 점과 리플렉션을 쓰기 때문에 프로가드를 통해 난독화를 해도 필드명이 노출되는 단점이 있습니다.


프로가드는 아래 링크를 참조해 주세요.

https://github.com/JakeWharton/butterknife/blob/master/butterknife/proguard-rules.txt



작가의 이전글 MVP unit test

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari