1. Android常用之Butterknife使用详解 https://segmentfault.com/a/1190000016460847
2. ButterKnife使用详解 https://www.jianshu.com/p/8256554dea6e
1. 引入依赖
1 2 3 4 |
dependencies { implementation 'com.jakewharton:butterknife:10.2.3' annotationProcessor 'com.jakewharton:butterknife-compiler:10.2.3' } |
2. 同步Gradle.
3. 使用:
1 2 3 4 5 6 |
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ...... ButterKnife.bind(this); } |
4. Butterknife Zelezny插件
使用场景:
在Activity中绑定View
1 2 3 4 5 6 7 8 9 |
class ExampleActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.simple_activity); ...... ButterKnife.bind(this); ...... } } |
1 2 3 4 5 |
@BindView(R.id.title) TextView title; @BindString(R.string.title) String title; @BindDrawable(R.drawable.graphic) Drawable graphic; @BindColor(R.color.red) int red; @BindDimen(R.dimen.spacer) Float spacer; |
在非Activity中
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public class FancyFragment extends Fragment { @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中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
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 { @BindView(R.id.title) TextView name; @BindView(R.id.job_title) TextView jobTitle; public ViewHolder(View view) { ButterKnife.bind(this, view); } } } |
View列表
1 2 |
@BindViews({ R.id.first_name, R.id.middle_name, R.id.last_name }) List<EditText> nameViews; |
apply函数可以让集合中的View执行相同的操作:
1 2 |
ButterKnife.apply(nameViews, DISABLE); ButterKnife.apply(nameViews, ENABLED, false); |
基于事件的绑定,方法名是自己定义的,没有过多要求,参数中的View也是可选的,可以加,可以不加:
1 2 3 4 5 6 7 8 9 |
@OnClick(R.id.submit) public void submit(View view) { // TODO submit data to server... } @OnClick(R.id.submit) public void sayHi(Button button) { button.setText("Hello!"); } |
Butter Knife提供了一个findViewById的简化代码:findById,用这个方法可以在View,Activity和Dialog中找到想要View,而且,该方法使用的泛型来对返回值进行转换,也就是说,你可以省去findViewById前面的强制转换了.强迫症的福因:
1 2 3 4 |
View view = LayoutInflater.from(context).inflate(R.layout.thing, null); TextView firstName = ButterKnife.findById(view, R.id.first_name); TextView lastName = ButterKnife.findById(view, R.id.last_name); ImageView photo = ButterKnife.findById(view, R.id.photo); |