No1:
添加依赖库
Project的build.gradle文件添加
buildscript{
...
dependencies{
...
classpath ‘com.neenbedankt.gradle.plugins:android-apt:1.8‘
}
}
在Module:app的build.gradle文件添加
apply plugin:‘com.neenbedankt.android-apt‘
...
dependencies{
...
compile ‘com.jakewharton:butterknife:8.4.0‘
apt ‘com.jakewharton:butterknife-compiler:8.4.0‘
}
No2:
绑定控件id
@BindView(R.id.tv_text)
TextView tv_text;
No3:
绑定资源
@BindString(R.string.app_name) String appName; @BindArray(R.array.swordsman) String[] swordsman; @BindDimen(R.dimen.activity_horizontal_margin) float margin;
No4:
绑定监听
@OnClick(R.id.bt_button1) public void showToast(){ } @OnLongClick(R.id.bt_button2) public boolean setText(Button button){ return true; }
@OnTextChanged(value=R.id.et_edittext,callback=OnTextChanged.Callback.BEFORE_TEXT_CHANGED) void beforeTextChanged(CharSequence s,int start,int count,int after){ } @OnTextChanged(value=R.id.et_edittext,callback=OnTextChanged.Callback.TEXT_CHANGED) void onTextChanged(CharSequence s,int start,int before,int count){ } @OnTextChanged(value=R.id.et_edittext,callback=OnTextChanged.Callback.AFTER_TEXT_CHANGED) void afterTextChanged(Editable s){ }
@OnTouch(R.id.bt_button3) public boolean onTouch(View view,MotionEvent event){ return true; } @OnItemClick(R.id.lv_list) void onItemClick(int position){ }
No5:
可选绑定
@Nullable
@BindView(R.id.tv_toptext)
TextView name;
No6:
ButterKnife注解处理器是ButterKnifeProcessor,主要处理逻辑都在process方法中
->findAndParseTargets
->brewJava
->createBinding
->findBindingConstructorForClass
->findRequiredViewAsType
->findRequiredView
->DecorView.findViewById
->castView