Search code examples
androiddeclare-styleable

Android library project uses declare-styleable -- how to compile?


I have a custom preferences control that I have defined a few attributes for in values/attrs.xml. Just to focus the conversation, here is an example of attributes that could be found in values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="android:text"/>
        <attr name="android:textColor"/>            
        <attr name="extraInformation" format="string" />
    </declare-styleable>
</resources>

To use the attributes, you use an xmlns tag where you want to use it, and it looks something like this:

xmlns:custom="http://schemas.android.com/apk/res/com.conundrum.app.lib"

Herein lies the problem: the xmlns definition refers to the LIBRARY's package name, and this resource compiles fine in the LIBRARY project. However, the Android project that includes the Library project has a different package name and Android tries to merge all the resources. When it gets to this xmlns definition, it balks because the package name is different in the including Android project.

Anybody got any ideas for using xmlns references in Library projects that are still valid in including Android projects?

Were declare-styleables just an oversight by the Android team when they considered libraries?


Solution

  • Use http://schemas.android.com/apk/res-auto

    I found this solution given casually as a side-note in the AndroidSVG project:

    Aside: Note the special schema URL in the namespace. If you were using a custom View from your own project you would use a URL based on your package name. For example http://schemas.android.com/apk/res/com.example.customview. But since the custom View is in an included library you should use the res-auto short-cut. The real schema URL will be automatically inserted when your app is built.

    (I fixed a typo - missing /res/ subfolder - in the quoted text above)