Android开发问题汇总(三)
1. How to define custom attributes?
A:Currently the best documentation is the source. You can take a look at it here(arrts.xml).
You can define attributes in the top <resources>
element or inside of a <declare-styleable>
element. If I’m going to use an attr in more than on place I put it in the root element. Note , all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable>
element it can be used outside of it and you cannot create another attribute with the same name of a different type.
An <attr>
element has two xml attributes name
and format
. name
lets you call it something and this how you end up refering to it in code, e.g., R.attr.my_attribute. The format
attribute can have different values depending on the type of attribute you want.
- reference - if it references another resource id(e.g, “@color/my_color”, “@layout/my_layout”)
- color
- boolean
- dimension
- float
- integer
- string
- fraction
- enum - normally implicitly defined
- flag - normally implicitly defined
You can set the format to multiple types by using |, e.g., format="reference|color"
.
enum attributes can be defined as follows:
1 2 3 4 |
|
flag attributes are similar except the values need to defined so they can be bit ored together:
1 2 3 4 |
|