Custom View:
The first step: Create a View implementation class, create a constructor and rewrite methods such as OnDraw () and Onmesure ().
Typedarray an array of properties for a custom view
The value of the corresponding property as defined in the styleable from the array
property is the name of the custom View + "-" + property name = = = Myview_textcolor
int textcolor = Array.getcolor (r.styleable. Myview_textcolor
Set the properties of the brush:Mpaint.setcolor (textcolor);
/*** This is a custom textview. * Requires at least overloaded construction methods and OnDraw methods * For custom view without its own unique properties, you can use it directly in the XML file * If you have your own unique attributes, you need to get the name of the custom attribute in the property file Attrs.xml in the constructor * and set default values as needed, which are not defined in the XML file. * If you use custom attributes, you need to add a new schemas to the application XML file, * This is xmlns:my= , for example .http://schemas.android.com/apk/res/demo.view.my " * where xmlns after" my "is a custom attribute prefix, res is the package where we customize the view *@authorAdministrator **/ Public classMyViewextendsView {Paint mpaint;//brushes that contain style and color information for drawing geometry, text , and so on PublicMyView (Context context) {Super(context); } PublicMyView (Context context, AttributeSet attrs) {Super(context, attrs); Mpaint=NewPaint (); //Typedarray is an array for storing properties obtained by Context.obtainstyledattributes//Be sure to call the Recycle method after use is complete//The name of the property is the name in Styleable + "_" + Property name TypedArray array = context.obtainstyledattributes (Attrs, R.styleable.myview); int textcolor = Array.getcolor (R.styleable.myview_textcolor, 0xff00ff00); Provide default value, place unspecified float textSize = array.getdimension (R.styleable.myview_textsize,); Mpaint.setcolor (TextColor); Mpaint.settextsize (textSize); array.recycle (); //Be sure to call, otherwise this time the setting will affect the next use } Public voidOnDraw (canvas canvas) {Super. OnDraw (canvas); //Canvas contains a lot of drawing interfaces, using these interfaces, we can draw the graphics we want//mpaint = new Paint (); //Mpaint.setcolor (color.red); Mpaint.setstyle (Style.fill);//Set the FillCanvas.drawrect (Ten, ten, N, Mpaint);//Draw a rectangleMpaint.setcolor (Color.Blue); Canvas.drawtext ("I was drawn," 10, 120. , Mpaint); } }
Step two: Create a attrs file under/res/values/, add <declare--styleable/>
<!--Custom Properties - <declare-styleablename= "MyView"> <attrname= "TextColor"format= "Color"/> <attrname= "TextSize"format= "Dimension"/> </declare-styleable>
Step three: Add namespaces to the layout file to facilitate referencing properties that are customized in the Attrs.xml file
Android Custom View (1)