Android custom components (I) basic implementation methods and Custom Attributes
Implementation Method:
1. inherit from ViewGroup or Layout and customize the position and size of the sub-view. It is used to combine some components to generate a composite component.
2. inherit your own widget View to extend the functions of existing components
3. inherit the custom View and completely customize a component
Constructor of the custom class:
Public CustomView2 (Context context) {// this function is used for calling in the Code;} public CustomView2 (context Context, AttributeSet attrs) {// when using a custom view in xml, use this function super (context, attrs);} public CustomView2 (Context context, AttributeSet attrs, int defStyle) {// super (context, attrs, defStyle) can be manually called by the previous function );}
In the custom function, attrs indicates the attribute set of the view, and defStyle indicates the id of the default attribute resource set.
Use a custom view in xml:
Custom property definition attributes res/values/attrs. xml
Used in Layout
Parse custom attributes in code
Public CustomView1 (Context context, AttributeSet attrs) {super (context, attrs); // atts includes TypedArray array = context. obtainStyledAttributes (attrs, R. styleable. customview1); // The System adds the name_int color = array of declare-styleable to the custom attribute. getColor (R. styleable. customview1_color, Color. WHITE); float rotation = array. getFloat (R. styleable. customview1_rotation, 0f); float score = array. getFraction (R. styleable. customview1_score, 0, 13, 10); array. recycle (); // reclaim System. out. println ("color =" + color + ", rotation =" + rotation + ", score =" + score); setBackgroundColor (color );}