Android Library 中的資源 id 不是 final

【流程】
ButterKnife 的說明中提到使用 R2 而非 R1
StackOverflow: 必須使用 R2 的情況僅限于 library,application 仍可以使用 R
理由:library 中的 R.id 不是 final,會變化
引申:library 中不能使用 switch-case 處理 資源 id
上面的解決辦法:使用 if-else
根源:Google 在 ADT14開始移除 library R 中的 final 標(biāo)記
why?有可能造成 id 碰撞,例如:在一個項目中使用了多個 library 的時候

貼上官方解釋:
http://tools.android.com/tips/non-constant-fields

In a regular Android project, constants in the resource R class are declared like this:
public static final int main=0x7f030004;

However, as of ADT 14, in a library project, they will be declared like this:
public static int main=0x7f030004;

In other words, the constants are not final in a library project. The reason for this is simple: When multiple library projects are combined, the actual values of the fields (which must be unique) could collide. Before ADT 14, all fields were final, so as a result, all libraries had to 【have all their resources and associated Java code recompiled along with the main project whenever they were used. This was bad for performance, since it made builds very slow. It also prevented distributing library projects that didn't include the source code, limiting the usage scope of library projects】.

The reason the fields are no longer final is that it means that the library jars can be compiled once and reused directly in other projects. As well as allowing distributing binary version of library projects (coming in r15), this makes for much faster builds.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容