Maven
<dependency> <groupId>com.jakewharton</groupId> <artifactId>butterknife</artifactId> <version>7.0.1</version> </dependency>Gradle
compile 'com.jakewharton:butterknife:7.0.1'
Activity绑定示例
class ExampleActivity extends Activity { @Bind(R.id.title) TextView title; @Bind(R.id.subtitle) TextView subtitle; @Bind(R.id.footer) TextView footer; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this);//绑定Activity // TODO Use fields... } }
Non Activity绑定示例
public class FancyFragment extends Fragment { @Bind(R.id.button1) Button button1; @Bind(R.id.button2) Button button2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fancy_fragment, container, false); ButterKnife.bind(this, view); // TODO Use fields... return view; } }View Holder绑定示例
public class MyAdapter extends BaseAdapter { @Override public View getView(int position, View view, ViewGroup parent) { ViewHolder holder; if (view != null) { holder = (ViewHolder) view.getTag(); } else { view = inflater.inflate(R.layout.whatever, parent, false); holder = new ViewHolder(view); view.setTag(holder); } holder.name.setText("John Doe"); // etc... return view; } static class ViewHolder { @Bind(R.id.title) TextView name; @Bind(R.id.job_title) TextView jobTitle; public ViewHolder(View view) { ButterKnife.bind(this, view); } } }监听器示例
//监听器也可以自动配置进方法中: @OnClick(R.id.submit) public void submit(View view) { // TODO submit data to server... } //监听方法的所有参数可以被操作: @OnClick(R.id.submit) public void submit() { // TODO submit data to server... } //定义一个具体的类型并且它将会自动的被类型转换 @OnClick(R.id.submit) public void sayHi(Button button) { button.setText("Hello!"); } //对通用事件操作时在一个单独的绑定中声明多个ID @OnClick({ R.id.door1, R.id.door2, R.id.door3 }) public void pickDoor(DoorView door) { if (door.hasPrizeBehind()) { Toast.makeText(this, "You win!", LENGTH_SHORT).show(); } else { Toast.makeText(this, "Try again", LENGTH_SHORT).show(); } } //自定义view可以绑定在他们自己的监听器上并且不需要具体声明一个ID public class FancyButton extends Button { @OnClick public void onClick() { // TODO do something! } }BINDING RESET
Fragment和Activity相比有不同的生命周期。当在一个Fragment的onCreateView中绑定的时候,需要在onDestoryView中设置Views为null。但是,Butter Knife 有一个 unbind 方法来自动的做这件事。
public class FancyFragment extends Fragment { @Bind(R.id.button1) Button button1; @Bind(R.id.button2) Button button2; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fancy_fragment, container, false); ButterKnife.bind(this, view); // TODO Use fields... return view; } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this);//解除绑定 } }
github:https://github.com/JakeWharton/butterknife
Introduction:http://jakewharton.github.io/butterknife/
示例版本为7.0.0,早前版本使用上有一定差别。