I need to implement my own attributes like in com.android.R.attr
Found nothing in official documentation so I need information about how to define these attrs and how to use them from my code.
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Currently the best documentation is the source. You can take a look at it here (attrs.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 one 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 attributesnameandformat.namelets you call it something and this is how you end up referring to it in code, e.g.,R.attr.my_attribute. Theformatattribute can have different values depending on the ‘type’ of attribute you want.You can set the format to multiple types by using
|, e.g.,format="reference|color".enumattributes can be defined as follows:flagattributes are similar except the values need to be defined so they can be bit ored together:In addition to attributes there is the
<declare-styleable>element. This allows you to define attributes a custom view can use. You do this by specifying an<attr>element, if it was previously defined you do not specify theformat. If you wish to reuse an android attr, for example, android:gravity, then you can do that in thename, as follows.An example of a custom view
<declare-styleable>:When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only
xmlns:android="http://schemas.android.com/apk/res/android". You must now also addxmlns:whatever="http://schemas.android.com/apk/res-auto".Example:
Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.
The end. 🙂