1. 程式人生 > >android library工程專案之間的相互引用出現的問題

android library工程專案之間的相互引用出現的問題

轉自:http://eyeandroid.diandian.com/post/2013-04-11/40049090256

當project主動引用另外一個android project的時候,出現了一個問題,在當前的project中報了library中的一些錯誤 :

E:\developtools\workspace\Chejt\res\layout\setting_contents_fragment.xml:62: error: No resource identifier found for attribute 'mode' in package 'com.souchenow.cjt<這是作為library的專案>'

在我們的library專案中確實用到了attribute,即xml自定義屬性,在attr.xml中定義了一些屬性,但是它不作為一個library的時候就不會報錯,而作為一個library的時候卻報了錯,這是什麼原因呢?我通過以下方式解決了問題,在xml中引入這個屬性的時候,我們不使用以前的

      xmlns:ptr="http://schemas.android.com/apk/com.shouchenow.main"

這樣的形式,而換成了

      xmlns:ptr="http://schemas.android.com/apk/res-auto"

換成了res-auto ,這樣問題解決,

詳細看下連結:

簡述:

Solution:

Upgrade to latest SDK & ADT version (fixed was released since r17) and usehttp://schemas.android.com/apk/res-auto as custom attributes' namespace URI, see Revisions for ADT 17.0.0:

Added support for custom views with custom attributes in libraries. Layouts using custom attributes must use the namespace URI 

http://schemas.android.com/apk/res-auto instead of the URI that includes the app package name. This URI is replaced with the app specific one at build time.

Related Topic:

2.我們來看資源打包問題:

When you build an application that depends on a library project, the SDK tools compile the library into a temporary JAR file and uses it in the main project, then uses the result to generate the .apk. In cases where a resource ID is defined in both the application and the library, the tools ensure that the resource declared in the application gets priority and that the resource in the library project is not compiled into the application .apk. This gives your application the flexibility to either use or redefine any resource behaviors or values that are defined in any library.

當我們把一個android project 加上 is library屬性的時候,再進行清理之後R檔案會出現以下的情況:

拿R.id來舉一個例子,在加上屬性以前為:

public static final class id {

      public static final int action_settings=0x7f080000;

  }

但是加上屬性之後會變成下面的形式:

public static final class id {

      public static int action_settings=0x7f080000;

  }

當加上is library屬性之後,在R檔案中的final屬性就會消失,而不是libary的時候,是會有final屬性的,如果變成了libary,我們在使用到R.id.button等的時候,我們就不能把它放在switch中,我們只能把它放在if()else()中,因為switch要求為常量,而if...else...沒有這樣的要求。

我們來看下當一個專案作為一個library引入之後如果資源衝突出現的情況來分析一下:

每個專案中都會有ic_lancher圖片,我們就用它來進行一個小小的連線前後的對比:

在連結前:library表示作為庫引入的專案,project表示我們將要引入包的那個專案。

library:public static final int ic_launcher=0x7f020000;

project:public static final int ic_launcher=0x7f020000;

連結後:

我們清理專案:

library:public static int ic_launcher=0x7f020000;//final 消失,但是id號沒變

project:

library.get.R:public static final int ic_launcher= 0x7f020000;

project.get.R:public static final int ic_launcher=0x7f020000;