Reprint-Two Good articles integrated Android custom controls

Source: Internet
Author: User
Tags gettext

Two good articles, a place to learn from each other, integrated into the collection

Separately reproduced from: http://blog.csdn.net/xu_fu/article/details/7829721

Http://www.cnblogs.com/0616--ataozhijia/p/4003380.html

The design of the view structure of the Android system also adopts the combination mode, that is, the view as the base class of all the graphs, viewgroup the view inheritance into the views container class, thus obtains the basic structure of the view part-tree structure

View defines the basic operation of the drawing

The basic operation is done by three functions: measure (), layout (), Draw (), and its interior contains onmeasure (), OnLayout (), OnDraw () three sub-methods respectively. Here's how:

1. Measure operation

The measure operation is primarily used to calculate the size of the view, which is the width and length of the view. Defined as the final type in view, requires that the subclass cannot be modified. The following function is also called in the measure () function:

(1) onmeasure (), the size of the view will be finalized here, that is to say measure is just a wrapper for onmeasure, subclasses can overwrite the Onmeasure () method to achieve their own calculation of the view size of the way, The calculation results are saved by setmeasureddimension (width, height).

2. Layout operation

The layout action is used to set where the view appears on the screen. Defined as the final type in view, requires that the subclass cannot be modified. There are two basic operations in the layout () function:

(1) setframe (l,t,r,b), l,t,r,b the specific position of the child view in the parent view, which is used to save these parameters;

(2) OnLayout (), in view, this function does nothing, provided the function is mainly for the ViewGroup type layout sub-view;

3. Draw operation

The draw operation takes advantage of the parameters obtained from the first two parts, displays the view on the screen, and completes the entire view drawing work. The subclass should also not modify the method because it internally defines the basic operation of the drawing:

(1) drawing the background;

(2) If you want the view to display the gradient box, there will be some preparation work;

(3) Draw the view itself, called the OnDraw () function. OnDraw () is an empty function in view, which means that the specific view has to override the function to implement its own display (for example, the process of drawing text TextView here). For ViewGroup, you do not need to implement this function, because as a container is "no content", it contains multiple sub-view, and the child view has implemented its own drawing method, so only need to tell the child view to draw their own, that is, the following Dispatchdraw () Method

(4) Draw a sub-view, which is the Dispatchdraw () function. In view this is an empty function, the specific view does not need to implement the method, it is specially prepared for the container class, that is, the container class must implement the method;

(5) If necessary (the application calls Setverticalfadingedge or Sethorizontalfadingedge), start drawing the gradient box;

(6) Draw the scroll bar;

From the above you can see that custom view requires a minimum of two methods to overwrite Onmeasure () and OnDraw ().

ViewGroupThe extended operation in:

First ViewGroup is an abstract class.

1, the measure process of the child view

(1) Measurechildren (), internally using a For loop sub-view traversal, call the measure () method of the child view, respectively;

(2) Measurechild (), measure for the specified child view, will be called by Measurechildren;

(3) Measurechildwithmargins (), taking into account the measure of margin and padding for the specified sub-view;

The above three methods are viewgroup provided by the 3 sub-view to measure the reference method, the designer needs to overwrite the onmeasure () in practice, and then the sub-view to traverse measure, this time can use the above three methods, Of course, you can also customize the method to traverse.

2, the layout of the child view process

In ViewGroup, OnLayout () is defined as the abstract type, which means that the specific container must implement this method to arrange the layout of the child view, the main consideration is the size of the view and the relative position relationship between the views, such as gravity, Layout_ Gravity

3. Draw process for child views

(1) Dispatchdraw (), this method is used to traverse the child view and then separately draw the sub-view, the method will first handle the layout animation (that is, the layout animation is handled here), if there is a layout animation will create a drawing time for each child view, Then there is a for loop that iterates through the sub-view to invoke the draw method of the child view (actually the drawchild () below);

(2) Drawchild (), which is used to specifically invoke the draw method of a child view, which first processes the view animation (that is, where the view animation is handled), and then calls the Child View Draw ().

From the above analysis, it can be seen that the custom viewgroup need to write a minimum of onmeasure () and OnLayout () method, wherein the Onmeasure method can directly call Measurechildren and other existing methods, And the OnLayout method requires the designer to complete the definition, generally do not need to overwrite the Dispatchdraw () and Drawchild () These two methods, because the above two methods have completed the basic thing. However, it is possible to do some special effects on this basis by covering it, such as

[Java]View PlainCopy print?
  1. @Override
  2. protected void Dispatchdraw (canvas canvas) {
  3. //TODO auto-generated method stub
  4. //  
  5. //You can do some processing here first, including the incoming canvas
  6. //  
  7. Super.dispatchdraw (canvas); //This will call Drawchild to draw the child view
  8. //  
  9. //After all the child views are drawn, there are some things you can do here, like drawing shadows.
  10. //  
  11. }

Other

From the above analysis, it can be seen that the drawing of view tree is a recursive process, from ViewGroup until all sub-view is finished drawing, then where is the source of all this (who initiated measure, layout and draw)? Of course it's at the source of the view tree--viewroot! , Viewroot contains the Performtraversal () method in the window's total container decorview,viewroot, which calls Decorview's measure, layout, draw method in turn to finish drawing the view tree.

Invalidate () method

The invalidate () method causes the view tree to redraw, and the status flag in view Mprivateflags has a flag bit drawn that the current view needs to be redrawn, that is, only the view with the flag bit drawn set will need to be redrawn. When the view calls the Invalidate () method, the current view's drawn flag is first set, followed by a loop call to Parent.invalidatechildinparent (), This causes the view to be traversed up and down from the current view until the root view is viewroot, and the process will drawn the views that need to be redrawn, and then viewroot call the Performtraversals () method to complete the drawing process of the view.

Reproduced http://blog.csdn.net/xu_fu/article/details/7829721"

Reference book "Android Kernel Anatomy"--New Year's Day

To develop a custom control: 1, understand how view works  2, write subclass 3 Inheriting from view, add attribute  4 for custom view class, draw control  5, respond to User message  6, customize callback function     A, view structure principle the design of the structure of the Android system also adopts the combination mode, that is, view as the base class of all the graphs, and viewgroup to view inheritance as the Views container class. View defines the basic operation of the drawing basic operation is done by three functions: measure (), layout (), Draw (), and its interior contains onmeasure (), OnLayout (), OnDraw () three sub-methods. Here's how: 1, Measure operations      measure operations are primarily used to calculate the size of the view, which is the width and length of the view. Defined as the final type in view, requires that the subclass cannot be modified. The measure () function also calls the following function:      (1) onmeasure (), the view size will be finalized here, that is, measure is just a wrapper over Onmeasure, Subclasses can override the Onmeasure () method to achieve their own calculation of the view size, and save the calculation results by setmeasureddimension (width, height).  2, layout actions      layout actions are used to set where the view appears on the screen. Defined as the final type in view, requires that the subclass cannot be modified. There are two basic operations in the layout () function:      (1) setframe (l,t,r,b), l,t,r,b the specific location of the child view in the parent view, which is used to save these parameters;      (2) onlayout (), this function does nothing in view, it is provided primarily for ViewGroup type layout sub-views;  3, draw operations       The draw operation takes advantage of the parameters obtained from the first two parts, displays the view on the screen, and completes the entire view drawing work. Subclasses should also not modify the method because it internally defines the basic operation of the drawing:      (1) Draw background;      (2) If you want the view to display a gradient box, this will doSome preparatory work;      (3) Draw the view itself, that is, call the OnDraw () function. OnDraw () is an empty function in view, which means that the specific view has to override the function to implement its own display (for example, the process of drawing text TextView here). For ViewGroup, you do not need to implement this function, because as a container is "no content", it contains multiple sub-view, and the child view has implemented its own drawing method, so only need to tell the child view to draw their own, that is, the following Dispatchdraw () Methods;      (4) Draw a sub-view, the Dispatchdraw () function. In view this is an empty function, the specific view does not need to implement the method, it is specially prepared for the container class, that is, the container class must implement the method;      (5) If necessary (the application calls Setverticalfadingedge or Sethorizontalfadingedge), start drawing the gradient frame;      (6) Draw the scrollbar;      From above you can see that custom view requires a minimum of two onmeasure () and OnDraw () methods.   The construction method of view Class 3 main implementations of creating custom controls: 1) Inherit existing controls to implement custom controls: mainly when the control to be implemented and the existing control are similar in many ways, by extending the existing controls to meet the requirements. 2) Implement a custom control by inheriting a layout file, which is typically done in this way when you make a composite control.     Note at this point, the OnDraw method is not used, the layout file of the custom control is loaded by Inflater in the construction ad, and then the graphical interface of the custom control is loaded in AddView (view). 3) Implement a custom control by inheriting the view class, using GDI to draw the component interface, which is generally not possible in either of these ways.   The two ways to customize view add properties are: 1) defined in the view class. Find the attribute name of the XML layout by using the AttributeSet introduced in the constructor, and then find the resource ID that corresponds to the reference to find the value. Case: Implement a picture with text (picture, text is OnDraw method redraw implementation)
 public class MyView extends View {private String mtext;    private int MSRC;    Public MyView (Context context) {super (context);        } public MyView (context context, AttributeSet Attrs) {Super (context, attrs);        int resourceId = 0;        int textid = Attrs.getattributeresourcevalue (null, "Text", 0);        int srcid = Attrs.getattributeresourcevalue (null, "SRC", 0);        Mtext = Context.getresources (). GetText (Textid). toString ();    MSRC = Srcid;        } @Override protected void OnDraw (canvas canvas) {Paint paint = new Paint ();        Paint.setcolor (color.red);                 InputStream is = Getresources (). Openrawresource (MSRC);                Bitmap Mbitmap = Bitmapfactory.decodestream (IS);                int bh = mbitmap.getheight ();            int bw = Mbitmap.getwidth ();        Canvas.drawbitmap (Mbitmap, 0,0, paint);        Canvas.drawcircle (Max, Max, n, paint);    Canvas.drawtext (Mtext, BW/2, (), paint); }}

Layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:layout_width=" match_parent "    android:layout_height=" match_parent "    android:o rientation= "vertical" >    <com.example.myimageview2.myview        android:id= "@+id/myview1"        android: Layout_width= "Wrap_content"        android:layout_height= "wrap_content"         text= "@string/hello_world"        Src= " @drawable/xh "/></linearlayout>

Property text, SRC is read in the constructor method of the custom view class.

2) Register properties for view through XML. Same as the standard properties provided by Android. Case: Implement a textual description of the ImageView (imageview+textview combination, text description, you can set the location in the layout file)
public class Myimageview extends LinearLayout {public Myimageview (context context) {super (context);        } public Myimageview (context context, AttributeSet Attrs) {Super (context, attrs);        int resourceId =-1;        TypedArray TypedArray = context.obtainstyledattributes (Attrs, R.styleable.myimageview);        ImageView IV = new ImageView (context);        TextView TV = new TextView (context);        int N = Typedarray.getindexcount ();            for (int i = 0; i < N; i++) {int attr = Typedarray.getindex (i);                        Switch (attr) {Case R.styleable.myimageview_oriental:resourceid = Typedarray.getint (                R.styleable.myimageview_oriental, 0); This.setorientation (ResourceId = = 1?)                LinearLayout.HORIZONTAL:LinearLayout.VERTICAL);            Break   Case R.styleable.myimageview_text:resourceid = Typedarray.getresourceid (                     R.styleable.myimageview_text, 0);                        Tv.settext (resourceId > 0? typedarray.getresources (). GetText (resourceId): TypedArray                . getString (R.styleable.myimageview_text));            Break Case R.styleable.myimageview_src:resourceid = Typedarray.getresourceid (r.styleable .                MYIMAGEVIEW_SRC, 0);                Iv.setimageresource (resourceId > 0 resourceid:r.drawable.ic_launcher);               Break        }} AddView (iv);        AddView (TV);    Typedarray.recycle (); }}

Attrs.xml the attribute declaration, the file is placed in the values directory

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Myimageview" >        <attr name= "Text" format= "reference|string" ></attr>        <attr name= "Oriental" >            < Enum Name= "Horizontal" value= "1" ></enum>            <enum name= "Vertical" value= "0" ></enum>        < /attr>        <attr name= "SRC" format= "Reference|integer" ></attr>    </declare-styleable>< /resources>
Mainactivity layout file: First define the namespace xmlns:uview= "Http://schemas.android.com/apk/res/com.example.myimageview2" (Com.example.myimageview2 is the package name you define in manifest) and can then be used as if using the system's properties: Uview:oriental= "Vertical"
<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:uview= "http// Schemas.android.com/apk/res/com.example.myimageview2 "    xmlns:tools=" Http://schemas.android.com/tools    " Android:layout_width= "Match_parent"    android:layout_height= "match_parent"    android:orientation= "vertical "    tools:context=". Mainactivity ">    <textview        android:layout_width=" wrap_content "        android:layout_height=" Wrap_ Content "        android:text=" @string/hello_world "/>    <com.example.myimageview2.myimageview        Android:id= "@+id/myimageview1"        android:layout_width= "wrap_content"        android:layout_height= "Wrap_ Content "        uview:text=" This is a picture stating "         uview:src=" @drawable/tw "        uview:oriental=" Vertical ">    < /com.example.myimageview2.myimageview></linearlayout>
Four, the control draws the OnDraw () five,

Six: ways to customize View

The Onfinishinflate () callback method, which is called after the application loads the component from XML and constructs an interface with it, Onmeasure () detects the size of the view component and its subcomponents onlayout () when the component needs to allocate its child components to the location, Large hours Onsizechange () when the size of the component is changed OnDraw () when the component is about to draw its contents onkeydown when a keyboard is pressed onkeyup when a keyboard is released Ontrackballevent When a trackball event occurs Ontouchevent onwindowfocuschanged (Boolean) when the component gets and loses focus when the touch event occurs Onatrrachedtowindow () The method onwindowvisibilitychanged (int) that fires when the component is put into a window Ondetachedfromwindow () when the component is detached from a window: The method that fires when the visibility of the window containing the component changes reprinted from: http://www.cnblogs.com/0616--ataozhijia/p/4003380.html

Reprint-Two Good articles integrated Android custom controls

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.