In this blog,
We have shown you how to make a custom attribute and how to reference color attribute in drawable.
How is define
You can define attributes in the top <resources>
element or inside of an <declare-styleable>
element.
Note: All attributes share the same global namespace. That means that even if you create a new attribute inside of an
<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 is how you end up referring to it in code, e.g.,R.attr.my_c_attribute
The format
attribute can have different values depending on the ‘type‘ of the 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
How to use
There are few simple steps,
- Define the colors for the specific theme in your colors file:
12345<?xml version="1.0" encoding="utf-8"?><resources><color name="my_link_color1">#0077CC</color><color name="my_link_color2">#626262</color></resources> - Create file res/values/attrs.xml with contents:
1234<?xml version="1.0" encoding="utf-8"?><resources><attr name="myLinkColor" format="reference" /></resources> - Suppose we have 2 themes in our styles.xml (
Theme1
andTheme2
) define:
1234567<style name="Theme1" parent="Theme.AppCompat.Light.DarkActionBar"><item name="myLinkColor">@color/my_link_color1</item></style><style name="Theme2" parent="Theme.AppCompat.Light.DarkActionBar"><item name="myLinkColor">@color/my_link_color2</item></style> - Use the color in the XML:
1android:textColor="?attr/myLinkColor"
Maybe this blog is helpable for you.
Source: https://github.com/android/