The book is connected to the
Create attributes in XML, and then use Typedarray to get the attributes in Java code, and then use attributes to do something. Example: Get the color in XML and assign it to paint.
1. Create a new attrs.xml under res/values/
[HTML]View Plaincopy
- <? XML version= "1.0" encoding="Utf-8"?>
- <resources>
- <declare-styleable name="CustomView2">
- <attr name="TextColor" format="color" />
- <attr name="textSize" format="Dimension" />
- </declare-styleable>
- </Resources>
- <!--name= "CustomView1" Control name gets Typedarray
- <!--name= "TextColor" corresponds to Test:textcolor--
- <!--format= "color" corresponding to the construction method A.getcolor (R.styleable.customview2_textcolor, 0xFFFFFFFF); -
Format details can be referenced http://blog.csdn.net/ethan_xue/article/details/7315064
2. The main view of the constructor function
[Java]View Plaincopy
- Public class CustomView2 extends View {
- private Paint MPaint2;
- private String MText = "DrawText";
- Public CustomView2 (context context, AttributeSet attrs) {
- Super (context, attrs);
- MPaint2 = new Paint ();
- //Typedarray is the array,1 that holds the resource. This array is obtained through the context, Attrs is the constructor that is passed in, corresponding to Attrs.xml
- TypedArray a = Context.obtainstyledattributes (Attrs, R.STYLEABLE.CUSTOMVIEW2);
- //Get attributes defined in XML, formatted as name _ property name followed by default value
- int textcolor = A.getcolor (R.styleable.customview2_textcolor, 0xFFFFFFFF);
- float textSize = a.getdimension (r.styleable.customview2_textsize, 35);
- Mpaint2.setcolor (TextColor);
- Mpaint2.settextsize (textSize);
- //In order to maintain consistency with this attribute later, return a binding resource to the end of the signal to the resource
- A.recycle ();
- }
- @Override
- protected void OnDraw (canvas canvas) {
- Super.ondraw (canvas);
- Mpaint2.setstyle (Style.fill);
- Canvas.drawtext (MText, Ten, mPaint2);
- }
- }
3. Layout
[HTML]View Plaincopy
- <? XML version= "1.0" encoding="Utf-8"?>
- <!--xmlns:test= "Http://schemas.android.com/apk/res/ethan.customview1" package name--
- <linearlayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:test="Http://schemas.android.com/apk/res/ethan.customview1"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- <ethan.customview1.CustomView2
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- test:textcolor="#f00"
- test:textsize="20sp"
- />
- </linearlayout>
4.
http://download.csdn.net/detail/ethan_xue/4108832
Android custom Controls (iii) custom properties