1. Customize a View File myview. Java
2. Define the custom property file values/attrs. xml
<? XML version = "1.0" encoding = "UTF-8"?>
<Resources>
<Declare-styleable name = "myatrr">
<ATTR name = "textcolor" format = "color"/>
<ATTR name = "textsize" format = "dimension"/>
</Declare-styleable>
</Resources>
3. Use custom views and attributes in the main layout File
Xmlns: MySpace = "http://schemas.android.com/apk/res/com.example.attrtest" // Add namespace, red for package name
<Com. example. attrtest. myview
Android: layout_width = "fill_parent"
Android: layout_height = "fill_parent"
MySpace: textsize = "25dp"
MySpace: textcolor = "# ff00ff00"
/>
Note: When textcolor is assigned, it is an 8-bit value. Otherwise, it will fail to be obtained in the program.
4. Get the custom attribute when the custom view is initialized
When the custom view is initialized in the layout file, the constructor of two parameters is called.
Typedarray TA = context. obtainstyledattributes (attrs, R. styleable. myatrr );
Int textcolor = TA. getcolor (R. styleable. myatrr_textcolor, color. Red );
Float textsize = TA. getdimension (R. styleable. myatrr_textsize, 30 );
The second parameter of both functions is the default value given when no custom attribute is added.
That's simple.
Source code: http://download.csdn.net/detail/wulongtiantang/5134371