Custom XML Attribute Flags
Flags are special attribute types in
that they are allowed only a very
small subset of values, namely those
that are defined underneath the
attribute tag. Flags are specified by
a “name” attribute and a “value”
attribute. The names are required to
be unique within that attribute type
but the values need not be. This is
the reason that during the evolution
of the Android platform we had
“fill_parent” and “match_parent” both
mapping to the same behavior. Their
values were identical.
The name attribute maps to the name
used in the value place within the
layout XML and does not require a
namespace prefix. Hence, for the
“tilingMode” above I chose “center” as
the attribute value. I could have
just as easily chosen “stretched” or
“repeating” but nothing else. Not
even substituting in the actual values
would have been allowed.
The value attribute must be an
integer. The choice of hexadecimal or
standard numeral representation is up
to you. There’s a few places within
the Android code where both are used
and the Android compiler is happy to
accept either.
Custom XML Attribute Enums
Enums are used in an almost identical
manner as flags with one provision,
they may be used interchangeably with
integers. Under the hood Enums and
Integers are mapped to the same data
type, namely, an Integer. When
appearing in the attribute definition
with Integers, Enums serve to prevent
“magic numbers” which are always bad.
This is why you can have an
“android:layout_width” with either a
dimension, integer, or named string
“fill_parent.”
To put this into context, let’s
suppose that I create a custom
attribute called
“layout_scroll_height” which accepts
either an integer or a string
“scroll_to_top.” To do so I’d add an
“integer” format attribute and follow
that with the enum:
<attr name="layout_scroll_height" format="integer">
<enum name="scroll_to_top" value="-1"/>
</attr>
The one stipulation when using Enums
in this manner is that a developer
using your custom View could
purposefully place the value “-1″ into
the layout parameters. This would
trigger the special case logic of
“scroll_to_top.” Such unexpected (or
expected) behavior could quickly
relegate your library to the “legacy
code” pile if the Enum values were
chosen poorly.
As I see it, the real values you can add in reality to an attribute is limited by what you can obtain from it. Check the AttributeSet
class reference here for more hints.