簡(jiǎn)介
ButterKnife 是一個(gè) Android 系統(tǒng)的 View 注入框架,能夠通過『注解』的方式來綁定 View 的屬性或方法。
比如使用它能夠減少 findViewById() 的書寫,使代碼更為簡(jiǎn)潔明了,同時(shí)不消耗額外的性能。
當(dāng)然這樣也有個(gè)缺點(diǎn),就是可讀性會(huì)差一些,好在 ButterKnife 比較簡(jiǎn)單,學(xué)習(xí)難度也不大。
ButterKnife 開源地址
https://github.com/JakeWharton/butterknife
配置
一下配置是基于 AS 的。
- 在Project 的 build.gradle 中添加
classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
示例代碼如下:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
//添加的插件
classpath 'com.jakewharton:butterknife-gradle-plugin:8.4.0'
}
}
- App 的 build.gradle 添加
compile 'com.jakewharton:butterknife:8.4.0'annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
示例代碼如下:
dependencies {
...........
compile 'com.jakewharton:butterknife:8.4.0'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0'
}
在Activity 中使用
在 activity 中使用需要在onCreate 方法中調(diào)用 ButterKnife.bind(this); 進(jìn)行綁定。
public class MainActivity extends AppCompatActivity {
@BindString(R.string.my_name) String name;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Toast.makeText(this,name,Toast.LENGTH_SHORT).show();
}
}
在Fragment 中使用
在 Fragment 中使用需要在 onViewCreated 方法中調(diào)用 ButterKnife.bind(this,view); 進(jìn)行綁定
public class ContenxtFragement extends Fragment {
@BindString(R.string.my_name) String name;
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ButterKnife.bind(this,view);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_context,container,false);
Button button = (Button) view.findViewById(R.id.open_fragment);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getContext(),name,Toast.LENGTH_SHORT).show();
}
});
return view;
}
}
常用綁定注解
注意: 使用注解不允許使用 private 或 static 進(jìn)行修飾
- @BindView(R.id.xxx) : 將對(duì)應(yīng)id綁定到指定view 上
@BindView(R.id.tab_index) Button mTabIndex;
@BindView(R.id.tab_find) Button mTabFind;
@BindView(R.id.tab_shop) Button mTabShop;
@BindView(R.id.tab_mine) Button mTabMine;
- @BindString(R.string.xxx) : 將對(duì)應(yīng)String資源中id對(duì)應(yīng)的輸入綁定到指定的String 變量上。
@BindString(R.string.my_name) String name;
- @OnClick(R.id.xxx) : 向ID為xxx的view綁定點(diǎn)擊事件
@OnClick(R.id.open_fragment)
public void showMsg(){
}
會(huì)有很多注解,使用都很簡(jiǎn)單。就不一一介紹了。