@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ButterKnife.bind(this); // TODO Use fields... } }
资源绑定
classExampleActivityextendsActivity{ @BindString(R.string.title) String title; @BindDrawable(R.drawable.graphic) Drawable graphic; @BindColor(R.color.red) int red; // int or ColorStateList field @BindDimen(R.dimen.spacer) Float spacer; // int (for pixel size) or float (for exact value) field // ... }
非Activity的绑定
public classFancyFragmentextendsFragment{ @BindView(R.id.button1) Button button1; @BindView(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; } }
绑定Adapter中ViewHolder
public class MyAdapter extends BaseAdapter { @Override public View getView(intposition, View view, ViewGroup parent) { ViewHolder holder; if (view != null) { holder = (ViewHolder) view.getTag(); } else { view = inflater.inflate(R.layout.whatever, parent, false); holder = newViewHolder(view); view.setTag(holder); }
holder.name.setText("John Doe"); // etc...
return view; }
static class ViewHolder { @BindView(R.id.title) TextView name; @BindView(R.id.job_title) TextView jobTitle;
public ViewHolder(View view) { ButterKnife.bind(this, view); } } }
绑定监听器
单击事件绑定:
@OnClick(R.id.submit) publicvoidsubmit(View view) { // TODO submit data to server... }