Custom views can also take custom attributes which can be used in Android layout resource files. To add attributes to your custom view you need to do the following:
1. Define the name and type of your attributes:
This is done inside res/values/attrs.xml (create it if necessary). The following file defines a color attribute for our smiley's face color and an enum attribute for the smiley's expression:
Use your attributes inside your layout:
This can be done inside any layout files that use your custom view. The following layout file creates a screen with a happy yellow smiley:
Tip: Custom attributes do not work with the tools: prefix in Android Studio 2.1 and older (and possibly in future versions). In this example, replacing app:smileyColor with tools:smileyColor would result in smileyColor neither being set during runtime nor at design time.
3. Read your attributes:
This is done inside your custom view source code. The following snippet of SmileyView demonstrates how the attributes can be extracted:
4. (Optional) Add default style:
This is done by adding a style with the default values and loading it inside your custom view. The following default smiley style represents a happy yellow one:
Which gets applied in our SmileyView by adding it as the last parameter of the call to obtainStyledAttributes (see code in step 3):
Note that any attribute values set in the inflated layout file (see code in step 2) will override the corresponding values of the default style.
5. (Optional) Provide styles inside themes:
Tthis is done by adding a new style reference attribute which can be used inside your themes and providing a style for that attribute. Here we simply name our reference attribute smileyStyle:
Which we then provide a style for in our app theme (here we just reuse the default style from step 4):