How do I declare an Android UI element using XML?

1 Like

The Android Developer Guide has a section called the discussion of XML attributes only covers declaring the control inside the layout file and not actually handling the values inside the class initialisation. The steps are as follows:

				Declare attributes in values\attrs.xml

		xml version="1.0" encoding="utf-8"?> 
		         name="extraInformation" format="string" /> 

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

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

		private void init(AttributeSet attrs){   
		        TypedArray a=getContext().obtainStyledAttributes(attrs,R.styleable.MyCustomView); 
		        //Use a 
		        Log.i("test",""+a.getColor(R.styleable.MyCustomView_android_textColor, Color.BLACK)); 
		        //Don't forget this 

R.styleable.MyCustomView is a int[] where each element is the ID of an attribute. Attributes are then retrieved from the TypedArray using various get functions. These attributes are not necessarily defined in the XML and so if the return value can't be null as a primitive is being returned, the second argument is the default value.

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 [b]not[/b] use anything in android.R.styleable, as per [this thread]( 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.

Include the namespace declaration xmlns:app="" in the top level xml element.

    android:text="Test text" 
app:extraInformation="My extra information";