今天自己尝试把一个项目当成Library引用的时候,新项目怎么编译都报一堆xml的error: No resource identifier found for attribute,无法生成R文件。目测初步断定原因是引用包内部xml资源识别之类的。不过clean了好多遍项目都不行。
于是尝试百度一下看有没解决方法。结果和平常一样,百度搜索引擎不行,搜出来结果大部分牛头不搭马嘴,比较相关的那些,解决方案又各种不痛不痒。
没办法,还是直接google吧。果然Stack Overflow的一个回答有比较接近了,“This <strong>wearable-support-lib</strong> contains some resources that cannot be packaged inside a <code>.jar</code> file”,但是提到的解决方法比较模糊。
不过很快就找到解决方案了(原po在这里https://devmaze.wordpress.com/2011/05/22/the-case-of-android-libraries-and-custom-xml-attributes-part-2/)。原po说得很清楚,但是因为用的是英文,这里针对自己的项目重新解释一下,一方面做个人解决方法记录总结,另一方面为遇到相同问题的程序猿提供个参考。
一、问题背景:
1.项目build target的版本是Android SDK2.2; 2.引用的Library项目中有自定义的XML属性
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:button="http://schemas.android.com/apk/res/com.android.test"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical" >
如果是独立运行的项目,这么运行是没有问题的,因为xmlns的后跟着的就是AndroidManifest.xml文件中定义的package命名空间:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.test" android:versionCode="1"
android:versionName="1.0">
二、问题产生原因:
Android应用程序在运行Android Library的时候是完全忽略Library的manifest的, Android Library的代码和xml资源几乎都是直接复制到Android应用程序文件夹中,所以基本上所有的属性都改成位于新项目的命名空间中。如果按原来代码编译就会在控制台报错:error: No resourceidentifier found for attribute。
三、解决方法:
使用 http://schemas.android.com/apk/res-auto取代原来的http://schemas.android.com/apk/res/app.package, 这样aapt tool就会识别并把当前Library的package属性作为命名空间。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:button="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="vertical">