Library中的R文件
前段時(shí)間跟項(xiàng)目老大提了個(gè)請求,就是將Butterknife加入到我們的項(xiàng)目中,結(jié)合android-butterknife-zelezny使用,這樣子不僅代碼簡潔,也可以減少一些findViewById的繁瑣過程,提升我們的開發(fā)效率.效果如下圖,是不是特別清爽,快捷.
![MacDown Screenshot](https://github.com/avast/android-butterknife-zelezny/raw/master/img/zelezny_animated.gif)
經(jīng)過老大的同意以后,我開始加依賴,下載自動(dòng)注解插件,進(jìn)行自動(dòng)生成代碼,一氣呵成,神清氣爽.But問題立馬就暴露出來了,代碼如下:
@OnClick({R2.id.m_button_pattern, R2.id.m_button_password})
public void onClick(View view) {
Log.d("xx", "========onClick=========");
Intent intent = new Intent();
switch (view.getId()) {
case R2.id.m_button_pattern:
intent.setClass(getApplicationContext(),MainActivity.class);
Log.d("xx", "========onClick====MainActivity=====");
break;
case R2.id.m_button_password:
intent.setClass(getApplicationContext(),SetPasswordLockActivity.class);
Log.d("xx", "========onClick=====SetPasswordLockActivity====");
break;
}
this.startActivity(intent);
}
然后問題就出現(xiàn)了.由于我們的項(xiàng)目是在Library中開發(fā)(蛋疼得不行,很多限制),問題就是出在這里,請看下面的代碼:
//Library中生成的R文件
public static int activity_open_exit=0x7f04000d;
//Module中生成的R文件
public static final int abc_fade_out=0x7f050001;
所以在Library中無法使用switch語句進(jìn)而影響到了Butterknife的使用.
至于為什么在Library中無法使用參考谷歌文檔.經(jīng)過閱讀我們知道從ADT14開始Library中的R文件才從靜態(tài)常量變?yōu)榉浅A?因?yàn)槿绻诙鄠€(gè)Library中可能出現(xiàn)id沖突的問題.在ADT14以前則采用的是將所有的資源文件和相關(guān)的代碼重新隨著主項(xiàng)目一起編譯,導(dǎo)致編譯速度過慢.因此,從ADT14開始就變成了非常量的id了:
int id = view.getId();
switch (id) {
case R.id.button1:
action1();
break;
case R.id.button2:
action2();
break;
case R.id.button3:
action3();
break;
}
Android Studio也提供了一鍵轉(zhuǎn)換的快捷方式如下圖:
![ConvertSwitch](http://tools.android.com/_/rsrc/1319062860174/tips/non-constant-fields/convert2.png)
然后就變成了如下所示的代碼了.
int id = view.getId();
if (id == R.id.button1) {
action1();
} else if (id == R.id.button2) {
action2();
} else if (id == R.id.button3) {
action3();
}
因?yàn)檎屹Y料的原因又去看了下Github的Butterknife, JakeWharton大神終于在大家的強(qiáng)烈請求下更新了支持Library, 更新日志;
Version 8.2.0 (2016-07-10)
New: Support for library projects. Requires application of a Butter Knife Gradle plugin. See README for details.
New: Generated code now emits R references instead of raw integer IDs.
Fix: @OnPageChange listener binding now uses the 'add'/'remove' methods on ViewPager instead of 'set'.
算是意料之外的驚喜吧,下周一就把Butterknife加入我們的項(xiàng)目!