Android框架ButterKnife的使用詳解,butterknife8.x.x版本的使用方法
阿新 • • 發佈:2018-12-30
butterknife是由Android大神JakeWharton所開發,專案地址
https://github.com/JakeWharton/butterknife/
- 1
這裡說一下8.1.0版本的使用,這個版本和以前的老版本使用方法修改了一下,不過也是比較簡單的。
首先我們要在Module中build.gradle增加引入庫:
/*增加註解的使用 butterknife*/
compile 'com.jakewharton:butterknife:8.8.1' annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
- 1
- 2
- 3
還有Module中build.gradle新增構建:
//apply plugin: 'com.android.library'apply plugin: 'com.jakewharton.butterknife'
- 1
然後我們需要在Project中build.gradle的depencises新增:
classpath 'com.jakewharton:butterknife-gradle-plugin:8.8.1'
repositories {
mavenCentral()
}
- 1
然後最後我們就可以使用我們的butterknife了。簡單寫一下Activity的使用:
@BindView(R.id.tv)
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
fragment中看官方使用瞭解綁,我在這裡這樣使用:
/**
* ButterKnife的使用,官方在fragment中使用瞭解綁
*/
protected Unbinder unbinder;
@BindView (R.id.tv)
TextView tv;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_main, container, false);
unbinder = ButterKnife.bind(this, rootView);
return rootView;
}
@Override
public void onDestroy() {
super.onDestroy();
unbinder.unbind();
}