share
Stack OverflowDeclaring a custom android UI element using XML
[+489] [6] Casebash
[2010-04-23 01:36:27]
[ xml android user-interface ]
[ https://stackoverflow.com/questions/2695646/declaring-a-custom-android-ui-element-using-xml ]

How do I declare an Android UI element using XML?

(16) If anyone looks for list of supported, built-in attribute formats, it can be found i.e. here. - Marcin Orlowski
(1) Good tutorial to get started with -> Creating Compound Views on Android - Gayan Weerakutti
[+849] [2010-04-23 01:36:36] Casebash [ACCEPTED]

The Android Developer Guide has a section called Building Custom Components [1]. Unfortunately, the discussion of XML attributes [2] only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:

1. Declare attributes in values\attrs.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="MyCustomView">
        <attr name="android:text"/>
        <attr name="android:textColor"/>            
        <attr name="extraInformation" format="string" />
    </declare-styleable>
</resources>

Notice the use of an unqualified name in the declare-styleable tag. Non-standard android attributes like extraInformation need to have their type declared. Tags declared in the superclass will be available in subclasses without having to be redeclared.

2. Create constructors

Since there are two constructors that use an AttributeSet for initialisation, it is convenient to create a separate initialisation method for the constructors to call.

private void init(AttributeSet attrs) { 
    TypedArray a=getContext().obtainStyledAttributes(
         attrs,
         R.styleable.MyCustomView);

    //Use a
    Log.i("test",a.getString(
         R.styleable.MyCustomView_android_text));
    Log.i("test",""+a.getColor(
         R.styleable.MyCustomView_android_textColor, Color.BLACK));
    Log.i("test",a.getString(
         R.styleable.MyCustomView_extraInformation));

    //Don't forget this
    a.recycle();
}

R.styleable.MyCustomView is an autogenerated int[] resource where each element is the ID of an attribute. Attributes are generated for each property in the XML by appending the attribute name to the element name. For example, R.styleable.MyCustomView_android_text contains the android_text attribute for MyCustomView. Attributes can then be retrieved from the TypedArray using various get functions. If the attribute is not defined in the defined in the XML, then null is returned. Except, of course, if the return type is a primitive, in which case the second argument is returned.

If you don't want to retrieve all of the attributes, it is possible to create this array manually.The ID for standard android attributes are included in android.R.attr, while attributes for this project are in R.attr.

int attrsWanted[]=new int[]{android.R.attr.text, R.attr.textColor};

Please note that you should not use anything in android.R.styleable, as per this thread [3] it may change in the future. It is still in the documentation as being to view all these constants in the one place is useful.

3. Use it in a layout files such as layout\main.xml

Include the namespace declaration xmlns:app="http://schemas.android.com/apk/res-auto" in the top level xml element. Namespaces provide a method to avoid the conflicts that sometimes occur when different schemas use the same element names (see this article [4] for more info). The URL is simply a manner of uniquely identifying schemas - nothing actually needs to be hosted at that URL [5]. If this doesn't appear to be doing anything, it is because you don't actually need to add the namespace prefix unless you need to resolve a conflict.

<com.mycompany.projectname.MyCustomView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:text="Test text"
    android:textColor="#FFFFFF"
    app:extraInformation="My extra information"
/> 

Reference the custom view using the fully qualified name.

Android LabelView Sample

If you want a complete example, look at the android label view sample.

LabelView.java [6]

 TypedArray a=context.obtainStyledAttributes(attrs, R.styleable.LabelView);
 CharSequences=a.getString(R.styleable.LabelView_text);

attrs.xml [7]

<declare-styleable name="LabelView">
    <attr name="text"format="string"/>
    <attr name="textColor"format="color"/>
    <attr name="textSize"format="dimension"/>
</declare-styleable>

custom_view_1.xml [8]

<com.example.android.apis.view.LabelView
    android:background="@drawable/blue"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    app:text="Blue" app:textSize="20dp"/>

This is contained in a LinearLayout with a namespace attribute: xmlns:app="http://schemas.android.com/apk/res-auto"

Links

[1] http://developer.android.com/guide/topics/ui/custom-components.html
[2] http://developer.android.com/guide/topics/ui/custom-components.html#modifying
[3] http://groups.google.com/group/android-developers/tree/browse_frm/thread/6554c6688f3ca6d9/8d018aa3f5c2beb9?rnum=1&_done=%2Fgroup%2Fandroid-developers%2Fbrowse_frm%2Fthread%2F6554c6688f3ca6d9%3Ftvc%3D1%26#doc_72f29c1df624bbed
[4] https://stackoverflow.com/questions/128389/what-are-xml-namespaces-forhttps://stackoverflow.com/questions/128389/what-are-xml-namespaces-for
[5] https://stackoverflow.com/questions/5758041/why-are-urls-in-xml-namespaces
[6] http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/LabelView.html
[7] http://developer.android.com/resources/samples/ApiDemos/res/values/attrs.html
[8] http://developer.android.com/resources/samples/ApiDemos/res/layout/custom_view_1.html
[9] https://stackoverflow.com/questions/2460074/how-to-retrieve-xml-attribute-for-custom-control
[10] https://stackoverflow.com/questions/2127177/how-do-i-use-obtainstyledattributesint-with-internal-themes-of-android
[11] https://stackoverflow.com/questions/3441396/defining-custom-attrs

(14) I would like to add that if your root element requires your custom namespace, you will have to add both the standard android namespace and your own custom one or else you may experience build errors. - Chase
(11) This answer is the clearest resource on the Internet on custom XML params that I was able to find. Thank you, Casebash. - Artem Russakovskii
Every thing is fine But I was confused in "R.styleable.MyCustomView_android_textColor" and did not know why you write MyCustomView_android_textColor But after search I knew that it is a fixed format "StylableName_AttributeName". So please explain little bit about it. Thanks for the great post. - Dharmendra
(2) for some reason , the visual editor refuses to use the written text value for android:text , yet the device uses it just fine . how come ? - android developer
(2) @androiddeveloper It seems that Eclipse editor refuses to use the values for all android: attributes. I would like to know if it is a feature or bug - deej
(1) Insane how bad the documentation is from Google, and that we have to always find posts somewhere to explain what should already be documented. - Reactgular
(4) What is the purpose of xmlns:app namespace and res-auto? - IgorGanapolsky
(1) This is getting ridiculous... I've been roaming the web for hours and every single answer leaves out the most important thing; How do I link my custom XML layout for the widget to my Java class, in a way that actually works? So far I still haven't gotten my widget to actually show up in my activity's layout. It's there, but I think the XML layout just doesn't get added to the parent view. - RobinJ
(2) @RobinJ: put this in the constructor(s) LayoutInflater.from(getContext()).inflate(R.layout.YOUR_LAYO‌​UT, this); - Andrew G
Is there any possibility to link a description to the attribute of the custom ui element. Something that is visible when I hover with the mouse over the attribute in the properties view of the designer in Eclipse? So far the tooltip of the attribute only says "attribute name" and underneath "[reference]". - Elementary
Great answer, thanks! Is there a way to make Android Studio suggest that reused attributes (for example android:text from the answer)? Currently it suggests app:android:text instead (since "app" is my custom namespace). - vir us
custom namespace ends in res-auto because we’re using Android Studio and Gradle. Otherwise (e.g. some Eclipse versions) it would usually end in lib/[your package name]. ie http://schemas.android.com/apk/lib/[your package name] - Universe
1
[+91] [2011-11-28 06:24:38] Andy

Great reference. Thanks! An addition to it:

If you happen to have a library project included which has declared custom attributes for a custom view, you have to declare your project namespace, not the library one's. Eg:

Given that the library has the package "com.example.library.customview" and the working project has the package "com.example.customview", then:

Will not work (shows the error " error: No resource identifier found for attribute 'newAttr' in package 'com.example.library.customview'" ):

<com.library.CustomView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.library.customview"
        android:id="@+id/myView"
        app:newAttr="value" />

Will work:

<com.library.CustomView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res/com.example.customview"
        android:id="@+id/myView"
        app:newAttr="value" />

(48) This has been ~fixed in ADT 17 preview. To use the app's namespace from the library declare xmlns:app="http://schemas.android.com/apk/res-auto" See comment 57 in code.google.com/p/android/issues/detail?id=9656 - nmr
(2) Including your custom namespace now returns an error Suspicious namespace: Did you mean http://schemas.android.com/apk/res-auto - Ben Wilkinson
custom namespace ends in res-auto because we’re using Android Studio and Gradle. Otherwise (e.g. some Eclipse versions) it would usually end in lib/[your package name] - Universe
custom namespace ends in res-auto because we’re using Android Studio and Gradle. Otherwise (e.g. some Eclipse versions) it would usually end in lib/[your package name]. ie http://schemas.android.com/apk/lib/[your package name] - Universe
2
[+27] [2013-02-28 14:35:27] yuriy.weiss

Addition to most voted answer.

obtainStyledAttributes()

I want to add some words about obtainStyledAttributes() usage, when we create custom view using android:xxx prdefined attributes. Especially when we use TextAppearance.
As was mentioned in "2. Creating constructors", custom view gets AttributeSet on its creation. Main usage we can see in TextView source code (API 16).

final Resources.Theme theme = context.getTheme();

// TextAppearance is inspected first, but let observe it later

TypedArray a = theme.obtainStyledAttributes(
            attrs, com.android.internal.R.styleable.TextView, defStyle, 0);

int n = a.getIndexCount();
for (int i = 0; i < n; i++) 
{
    int attr = a.getIndex(i);
    // huge switch with pattern value=a.getXXX(attr) <=> a.getXXX(a.getIndex(i))
}
a.recycle();

What we can see here?
obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
Attribute set is processed by theme according to documentation. Attribute values are compiled step by step. First attributes are filled from theme, then values are replaced by values from style, and finally exact values from XML for special view instance replace others.
Array of requested attributes - com.android.internal.R.styleable.TextView
It is an ordinary array of constants. If we are requesting standard attributes, we can build this array manually.

What is not mentioned in documentation - order of result TypedArray elements.
When custom view is declared in attrs.xml, special constants for attribute indexes are generated. And we can extract values this way: a.getString(R.styleable.MyCustomView_android_text). But for manual int[] there are no constants. I suppose, that getXXXValue(arrayIndex) will work fine.

And other question is: "How we can replace internal constants, and request standard attributes?" We can use android.R.attr.* values.

So if we want to use standard TextAppearance attribute in custom view and read its values in constructor, we can modify code from TextView this way:

ColorStateList textColorApp = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;

Resources.Theme theme = context.getTheme();

TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.CustomLabel, defStyle, 0);
TypedArray appearance = null;
int apResourceId = a.getResourceId(R.styleable.CustomLabel_android_textAppearance, -1);
a.recycle();
if (apResourceId != -1)
{
    appearance = 
        theme.obtainStyledAttributes(apResourceId, new int[] { android.R.attr.textColor, android.R.attr.textSize, 
            android.R.attr.typeface, android.R.attr.textStyle });
}
if (appearance != null)
{
    textColorApp = appearance.getColorStateList(0);
    textSize = appearance.getDimensionPixelSize(1, textSize);
    typefaceIndex = appearance.getInt(2, -1);
    styleIndex = appearance.getInt(3, -1);

    appearance.recycle();
}

Where CustomLabel is defined:

<declare-styleable name="CustomLabel">
    <!-- Label text. -->
    <attr name="android:text" />
    <!-- Label text color. -->
    <attr name="android:textColor" />
    <!-- Combined text appearance properties. -->
    <attr name="android:textAppearance" />
</declare-styleable>

Maybe, I'm mistaken some way, but Android documentation on obtainStyledAttributes() is very poor.

Extending standard UI component

At the same time we can just extend standard UI component, using all its declared attributes. This approach is not so good, because TextView for instance declares a lot of properties. And it will be impossible to implement full functionality in overriden onMeasure() and onDraw().

But we can sacrifice theoretical wide reusage of custom component. Say "I know exactly what features I will use", and don't share code with anybody.

Then we can implement constructor CustomComponent(Context, AttributeSet, defStyle). After calling super(...) we will have all attributes parsed and available through getter methods.


do android:xxx predefined attributes work in eclipse gui designer? - deej
Such attributes are recognized by Eclipse ADT plugin in property editor. I can see defaults from my style, if some values are not defined. And don't forget to add @RemoteView annotation to your class. - yuriy.weiss
Can't make it work. Eclipse keeps loading nulls for getText and throwing android.content.res.Resources$NotFoundException for getResourceId, though the app runs well on a device. - deej
Sorry, I can't help you. I have created only demo project to test possibilities, and not met such errors. - yuriy.weiss
This is so much better than mapping custom attributes of a custom view to the built-in attributes of built-in views contained within. - samus
3
[+13] [2012-06-29 07:19:59] mitch000001

It seems that Google has updated its developer page and added various trainings there.

One of them deals with the creation of custom views and can be found here [1]

[1] http://developer.android.com/training/custom-views/index.html

4
[+5] [2013-05-03 20:00:36] user2346922

Thanks a lot for the first answer.

As for me, I had just one problem with it. When inflating my view, i had a bug : java.lang.NoSuchMethodException : MyView(Context, Attributes)

I resolved it by creating a new constructor :

public MyView(Context context, AttributeSet attrs) {
     super(context, attrs);
     // some code
}

Hope this will help !


5
[0] [2015-02-04 08:16:50] Akshay Paliwal

You can include any layout file in other layout file as-

             <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="30dp" >

                <include
                    android:id="@+id/frnd_img_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_imagefile"/>

                <include
                    android:id="@+id/frnd_video_file"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    layout="@layout/include_video_lay" />

                <ImageView
                    android:id="@+id/downloadbtn"
                    android:layout_width="30dp"
                    android:layout_height="30dp"
                    android:layout_centerInParent="true"
                    android:src="@drawable/plus"/>
            </RelativeLayout>

here the layout files in include tag are other .xml layout files in the same res folder.


(1) I've tried this, the problem I have with it is that the included layout cannot be 'adapted', cannot create generics. For example when I include a button in a similar manner, if I try to set the text in the xml it does work. - cfl
6