Start a Project

How to create the custom attributes to reference color from style.xml in android

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.

How to use

There are few simple steps,

  1. Define the colors for the specific theme in your colors file:
  2. Create file res/values/attrs.xml with contents:
  3. Suppose we have 2 themes in our styles.xml (Theme1 and Theme2) define:
  4. Use the color in the XML:

     

Maybe this blog is helpable for you.

Source: https://github.com/android/

Exit mobile version