Home » Android » Android – custom UI with custom attributes

Android – custom UI with custom attributes

Posted by: admin March 11, 2020 Leave a comment


I know it is possible to create custom UI element (by way of View or specific UI element extension). But is it possible to define new properties or attributes to newly created UI elements (I mean not inherited, but brand new to define some specific behavior I am not able to handle with default propertis or attributes)

e.g. element my custom element:


So is it possible to define MyCustomValue?


How to&Answers:

Yes. Short guide:

1. Create an attribute XML

Create a new XML file inside /res/values/attrs.xml, with the attribute and it’s type

<?xml version="1.0" encoding="UTF-8"?>
    <declare-styleable name="MyCustomElement">
        <attr name="distanceExample" format="dimension"/>

Basically you have to set up one <declare-styleable /> for your view that contains all your custom attributes (here just one). I never found a full list of possible types, so you need to look at the source for one I guess. Types that I know are reference (to another resource), color, boolean, dimension, float, integer and string. They are pretty self-explanatory

2. Use the attributes in your layout

That works the same way you did above, with one exception. Your custom attribute needs it’s own XML namespace.


Pretty straight forward.

3. Make use of the values you get passed

Modify the constructor of your custom view to parse the values.

public MyCustomElement(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0);
    try {
        distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f);
    } finally {
    // ...

distanceExample is a private member variable in this example. TypedArray got lot’s of other things to parse other types of values.

And that’s it. Use the parsed value in your View to modify it, e.g. use it in onDraw() to change the look accordingly.


In your res/values folder create attr.xml. There you can define your attribues:

<declare-styleable name="">
    <attr name="myCustomValue" format="integer/boolean/whatever" />

When you then want to use it in your layout file you have to add


and then you can use the value with customname:myCustomValue=""


Yes , you can.Just use <resource> tag.
like this:

<?xml version="1.0" encoding="utf-8"?>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>

link from official website