Generally we are using android:xxx= "" ... The properties of such Android. But sometimes we need to use custom properties, especially when customizing the view.
The following steps are generally required:
1. define a attrs.xml file under the res/values file:
<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable name= "MyView" > <attr name= "TextColor" format= "color"/> <attr name= "textSize" format= "Dimension"/> </ Declare-styleable> </resources>
2. Rewrite Our custom view construction method. is to useR.styleable.myview Get our custom properties.
TypedArray usually last called . Recycle () method, in order to maintain consistency after using this attribute!
Package Com.example.viewdemo;import Android.annotation.suppresslint;import Android.content.context;import Android.content.res.typedarray;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.paint.style;import Android.graphics.rect;import Android.util.attributeset;import Android.view.view;public class MyView extends view{private Paint mpaint; Private Context Mcontext; private static final String mstring = "oh,god!"; Public MyView (Context context) {super (context); } public MyView (Context Context,attributeset attrs) {super (context,attrs); Mpaint = new Paint (); TypedArray a = context.obtainstyledattributes (Attrs,r.styleable.myview); int textcolor = A.getcolor (R.styleable.myview_textcolor, 0XFFFFFF);//Note Add default value float textSize = a.getdimension (r.style Able. Myview_textsize, 36); Mpaint.settextsize (textSize); Mpaint.setcolor (TextColor); A.recycLe (); } @Override protected void OnDraw (canvas canvas) {super.ondraw (canvas); Set the Fill Mpaint.setstyle (Style.fill); Draw a rectangle, the first two are the coordinates of the upper left corner of the rectangle, the following two are the lower right corner coordinates canvas.drawrect (new Rect (Ten, Ten, Nine), mpaint); Mpaint.setcolor (Color.Blue); Draw Text Canvas.drawtext (mstring, ten, mpaint); }}
3. Use our custom attributes in the XML layout file. Note Prefix
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:test= "http// Schemas.android.com/apk/res/com.example.viewdemo " android:layout_width=" match_parent " android:layout_ height= "Match_parent" android:orientation= "vertical" > <com.example.viewdemo.myview Android:layout_width= "Match_parent" android:layout_height= "wrap_content" test:textsize= "40px " Test:textcolor= "#fff" /></linearlayout>
Operating effect:
Android expert on the path of Android custom properties Attr.xml, Typedarray use