Sometimes our custom view needs to have its own attributes.
First, define your own attributes in RES/values/attrs. xml. The XML file is as follows:
<?xml version="1.0" encoding="utf-8"?><resources> <declare-styleable name = "myView"> <attr name = "text" format = "string" /> <attr name = "textSize" format = "dimension"/> <attr name = "textColor" format = "color"/> <attr name = "rectColor" format = "color"/> </declare-styleable></resources>
The name attribute is important for future calls.
Format is the attribute type. Several Basic data types are listed here. Note that textsize and other attribute formats related to the size are dimension.
In the layout file.
<Relativelayout xmlns: Android = "http://schemas.android.com/apk/res/android" xmlns: My = "http://schemas.android.com/apk/res/com.example.myview" Android: layout_width = "match_parent" Android: layout_height = "match_parent" Android: gravity = "center"> <COM. example. myview. myview Android: layout_width = "100dp" Android: layout_height = "100dp" My: text = "click to start counting" My: textcolor = "# ffff0000" My: textsize = "21sp" My: rectcolor = "# ff00ff00"/> </relativelayout>
Xmlns: My = "http://schemas.android.com/apk/res/com.example.myview" for use
Key code for calling custom attributes in my field.
When using my: XXX, the correctness of the attributes is not verified.
However, it will be verified when obtaining the attribute value in the Custom view code.
Obtains the property value to initialize the custom view.
// Obtain the attribute array private void initattrs (attributeset attrs) {mpanit = new paint (); mbound = new rect (); setonclicklistener (this); // and ATTR in the XML file. the attribute list in XML corresponds to typedarray TA = getcontext (). obtainstyledattributes (attrs, R. styleable. myview); string text = TA. getstring (R. styleable. myview_text); settext (text); int textsize = TA. getdimensionpixeloffset (R. styleable. myview_textsize, 26); settextsize (textsize); int color = TA. getcolor (R. styleable. myview_textcolor, 0xff000000); settextcolor (color); int rectcolor = TA. getcolor (R. styleable. myview_rectcolor, 0xff000000); setrectcolor (rectcolor); TA. recycle ();}
Attributeset attrs is the attribute in XML and its corresponding value.
Typedarray TA = getcontext (). obtainstyledattributes (attrs, R. styleable. myview );
Only get the attributes in the custom property name myview. And assign it to typearray TA.
Then you can obtain the corresponding attribute value based on the TA.
As for how to use the obtained property values, it depends on your own.
Custom attribute usage in custom view.