How is declare-stylable name linked to the view that uses its attributes?

922 Views Asked by At

Usually al examples of custom attributes are of the form:

<declare-stylable name="MyView">
    <attr name="name" format="string"/>
</declare-styleable>  

and its usage:

<com.example.test.MyView
    customns:name="Hello"/>

So the custom view has the same name as the stylable attributes.

But in this example (click for full code) you see:

<declare-styleable name="Options">
    <attr name="titleText" format="string" localization="suggested" />
    <attr name="valueColor" format="color" />
</declare-styleable>

used by:

<com.vogella.android.view.compoundview.ColorOptionsView
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeight"
    custom:titleText="Background color"
    custom:valueColor="@android:color/holo_green_light"
    />

It made me wonder, how is it that ColorOptionsView was linked to the attributes defined with name Options?

1

There are 1 best solutions below

6
On

Those options are available as part of the declared namespace custom, which is included at the top of the XML file:

xmlns:custom="http://schemas.android.com/apk/res/com.vogella.android.view.compoundview"

NOTE

Simply adding this line will not provide support for auto-complete. If that is what your mean by your question, you need to add the schema to your workspace's XML Catalog. You can do this in Eclipse by going to Eclipse -> Preferences, then XML -> XML Catalog. Here, click the Add... button. Navigate to the XML Schema file, then select OK. If you close and re-open the the XML file, you will now have autocompletion.


Finally, when unpacking the attributes used in ColorOptionsView.java, the author can specifically look for attributes from this namespace. This is from the same source (commented by me):

//grab the declared-styleable resource entries
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Options, 0, 0);
//get the "titleText" entry from this element's attributes
String titleText = a.getString(R.styleable.Options_titleText);
//get the "valueColor" attribute. If it does not exists, set the default to holo_blue_light
int valueColor = a.getColor(R.styleable.Options_valueColor,
    android.R.color.holo_blue_light);
a.recycle();