如果還沒看看前2篇的請移步
使用annotationProcessor打造編譯時的注解(一)
使用annotationProcessor打造編譯時的注解(二)
這篇主要是對點擊事件的實現(xiàn)
先看生成的類
public class MainActivity_ViewBinding implements Unbinder {
private MainActivity target;
private View view2131165218;
@UiThread
public MainActivity_ViewBinding(final MainActivity target, View source) {
this.target = target;
target.textView = source.findViewById(2131165323);
View view2131165218 = source.findViewById(2131165218);
this.view2131165218 = view2131165218;
view2131165218.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
target.onClick(view);
}
});
}
@Override
public void unbind() {
MainActivity target = this.target;
this.target = null;
target.textView = null;
view2131165218.setOnClickListener(null);
view2131165218 = null;
}
}
如果父類中也有用到butterknife的話枫绅,那么生成的類是這樣的
public class BaseNormalActivity_ViewBinding extends BaseActivity_ViewBinding {
private BaseNormalActivity target;
@UiThread
public BaseNormalActivity_ViewBinding(final BaseNormalActivity target, View source) {
super(target, source);
this.target = target;
target.textView = source.findViewById(2131165323);
}
@Override
public void unbind() {
BaseNormalActivity target = this.target;
this.target = null;
target.textView = null;
super.unbind();
}
}
public class MainActivity_ViewBinding extends BaseNormalActivity_ViewBinding {
private MainActivity target;
private View view2131165218;
@UiThread
public MainActivity_ViewBinding(final MainActivity target, View source) {
super(target, source);
this.target = target;
target.textView2 = source.findViewById(2131165324);
View view2131165218 = source.findViewById(2131165218);
this.view2131165218 = view2131165218;
view2131165218.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
target.onClick(view);
}
});
}
@Override
public void unbind() {
MainActivity target = this.target;
this.target = null;
target.textView2 = null;
view2131165218.setOnClickListener(null);
view2131165218 = null;
super.unbind();
}
}
當(dāng)然使用和butterknife完全一樣
@BindView(R.id.textView2)
TextView textView2;
@OnClick({R.id.bt_click, R.id.bt_click2})
public void onClick(View view) {
}
這里對上一篇的代碼進行了重構(gòu)裁着,因為注解處理器需要同時支持BindView和OnClick注解,所以就再創(chuàng)建了一個注解處理器ViewProcessor,之前的BindViewProcessor處理器在項目中沒有刪掉慰安,但是不能處理注解了不瓶,只作為參考代碼。
ViewProcessor的代碼量還是有一點的,如果你從來沒有接觸編譯時的注解户敬,可能看完這代碼會導(dǎo)致你身體不適,在這里表示抱歉睁本,但是還是靜下來心來慢慢品嘗尿庐,你肯定會有收獲的。一些注釋在代碼中已經(jīng)標(biāo)示的很清楚呢堰,三言兩語我也說不清楚抄瑟,我也不準(zhǔn)備在這一一解釋每行代碼的作用是什么,每個字段作用是什么枉疼,如果需要深入了解就把代碼下載下來慢慢調(diào)試皮假。