Android
Butter Knife 라이브러리
밤토리세상
2020. 9. 24. 18:48
findViewById 를 이용하여 UI를 연결하는 것을 간소화 등의 다양한 기능제공
https://github.com/JakeWharton/butterknife
JakeWharton/butterknife
Bind Android views and callbacks to fields and methods. - JakeWharton/butterknife
github.com
해당 링크에 자세한 내용 확인 가능
안드로이드 스튜디오 기준으로 작성하였습니다
-설치하기
app: gradle 에 해당 내용 작성
android {
...
// Butterknife requires Java 8.
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
implementation 'com.jakewharton:butterknife:10.2.3'
annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3'
}
프로젝트: gradle 에 해당 내용 작성
buildscript {
repositories {
mavenCentral()
google()
}
dependencies {
classpath 'com.jakewharton:butterknife-gradle-plugin:10.2.3'
}
}
모듈 gradle 에 해당 내용 작성
apply plugin: 'com.android.library'
apply plugin: 'com.jakewharton.butterknife'
- 사용방법
기존에 XML에서 작성한 레이아웃등을 연결하기위해서 사용하던 findViewById 대신에 사용하면된다
우선 onCreate() 에서 setContentView 뒤에 ButterKnife.bind(this) 를 호출하여 bind 시켜주어야 한다
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
ButterKnife.bind(this);
}
onCreate 내부에서 findViewById 로 각각의 뷰를 찾아서 연결해 주었다면 해당 라이브러리를 이용하여 한번에 가능하다
public class Activity extends AppCompatActivity {
@BindView(R.id.btn) Button btn;
@BindView(R.id.et_search) EditText et_search;
@BindView(R.id.search_btn)
Button search_btn;
...
}
위처럼 한줄에 작성을 하여도 되고
한줄을 띄워서 작성을 하여도 가능하다
여러개 쭉 있을때 줄을 바꾸어서 해놓는게 개인적으로는 좀 더 보기 좋아서 아래의 한칸 띄워서 사용하고있다
해당 라이브러리를 사용하고 BindView를 해주면 바로 해당 변수명을 불러서 사용이 가능하다