Custom view, which can also be called a custom control, allows the control to achieve a variety of custom effects by customizing the view.
To implement a custom view, you need to master the underlying workings of the view, such as the view's measurement process, the layout process, and the drawing process, in addition to the view's common callback methods. For custom view that has a sliding effect, we also need to handle the slide of the view, and if we encounter a sliding conflict, we need to handle the corresponding sliding conflict.
The following are common callback methods for view:
- Construction method
- Onattach
- Onvisibilitychanged
- Ondetach
- Onfinishinflate
- Onsizechanged
- Onmeasure
- OnLayout
- Ontouchevent
The implementation of custom controls can be briefly divided into four categories:
- Inherit view override OnDraw method, which is mainly used to implement some irregular effects, in this way need to support wrap_content, and handle padding.
- Inheritance ViewGroup derives special layout, which is primarily used to implement custom layouts, which can be implemented when an effect looks like a couple of view combinations. It is necessary to deal with the measurement and layout of ViewGroup and to deal with the measurement and layout process of the sub-elements.
- Inherit a specific view to extend the functionality of an existing view.
- Inheriting specific viewgroup, such as LinearLayout, Relativelayout, is similar to the case for Method 2.
Points to note in Custom view:
Specifications for Android standard controls (such as naming, configurable, event handling, state saving and recovery, etc.) should be adhered to
- The naming table means clear
- Control properties can be configured in XML
- Let view support wrap_content and padding (detailed below)
- Try not to use handler in view because of the method that comes with the Post series in view.
- Custom View memory leak problem (if thread or animation needs to be stopped in time)
- View sliding conflict (when the view has a sliding nesting situation, you need to handle the sliding conflict)
- With a certain degree of interactivity, such as press, click, etc.
- Custom view internal implementation of State saving and recovery mechanisms
- Compatibility
The following is mainly from the basic knowledge of the view, view of the drawing process to tell how the view works.
1. Speaking from the view structure in activity
Each activity contains a Window object, and the Window object is generally phonewindow. Phonewindow will set the Decorview to the root view of the entire application window. Decorview as the top-level view of the window interface, encapsulates some common methods for window manipulation. So to speak, Decorview will show the specific content in the Phonewindow, which all the view of the monitoring events are received through the Windowmanagerservice, And the corresponding onclicklistenr are adjusted back and forth through the activity object.
In the display, the screen is divided into two parts, one is Titleview, the other is Contentview, this contentview presumably everyone is familiar with, it is an ID content of the Framelayout,activity_ The main is set in such a framelayout.
As shown in Fig. 1 and Figure 2:
Figure 1
Figure 2
The drawing process for view:
Figure 3
As shown, Performtraversals will call Performmeasure, PerformLayout, Performdraw three methods, the three methods to complete the top view of the measure, layout, Draw these three great processes.
In the performmeasure, the measure is called, then the Onmeasure method is called in measure, and all the child elements are onmeasure in measure. At this point, the measure process is passed from the parent container to the child element, which completes the measure operation, then the child elements perform the same measure process until the entire view tree is traversed. Similarly, the transfer process of performlayout and Performdraw is similar to the performmeasure (the Performdraw transfer process is done in the dispatchdraw of the draw method, and there is no real difference).
The measure process determines the width of the view, and after the measure is complete, the Getmeasuredwidth and Getmeasuredheight methods are used to obtain the width of the view measurement, which in almost all cases equates to the final height of the view, Except in special cases. The layout process determines the coordinates of the four vertices of the view and the actual view width, and after completion, the positions of the four vertices can be obtained by GetTop, Getbottom, GetLeft, GetRight. The final width and height of the view can be obtained by getwidth and GetHeight. The draw process determines the display of the view, and the contents of the view are displayed on the screen only after the Draw method is completed.
2. How do I complete the measurement process?
The Android system provides a Measurespec class that helps us measure the view. The Measurespec is a 32-bit int value with a height of 2 bits in the measured mode and a low 30 bit for the measured size.
exactly: The exact value mode, when we specify the Layout_width or Layout_height property of the space as a specific value, or when specified as the Match_parent attribute, the system uses exactly.
at_most: Maximum mode, when the Layout_width property of a space or the Layout_height property is Wrap_content, the size of the control generally varies with the child controls or the content of the space, at which point The size of the control can be as long as it does not exceed the maximum size allowed by the parent control.
UNSPECIFIED: Does not specify its measurement size, which is normally used when drawing a custom view.
During the measurement of the view, the system converts the Layoutparams to the corresponding measurespec under the constraints of the parent container, and then determines the width height of the view measurement based on the Measurespec. Measurespec is determined by both the parent container and the layoutparams.
For Decorview, its measurespec is determined by the size of the window and its own layoutparams
For a normal view, its measurespec is determined by the parent container's measurespec and its own layoutparams
When the layoutparams of a view takes an exact value, the MEASURESPEC mode of the view is exactly, regardless of the parent container's measurespec, and the size follows the layoutparms size.
When the width of the view is Match_parent mode, the view's Measurespec mode follows the Measurespec mode of the parent container.
When the width of the view is wrap_content, the mode of the parent container is at_most and the size does not exceed the remaining space of the parent container, regardless of the mode of the exactly or At_most,view.
The following sections briefly describe the measure process of view and the measure process of viewgroup.
1) View measure process:
Reference Source:
protected void onmeasure (intint heightmeasurespec) { setmeasureddimension (getdefaultsize (Getsuggestedminimumwidth (), Widthmeasurespec), getdefaultsize (Getsuggestedminimumheight (), Heightmeasurespec));}
Figure 4
It is known from the above source that the Setmeasureddimension method is called when calling the Onmeasure method, in which the width of the method is passed in. So, in a custom view, you need to redefine the width and height of the view.
The default Onmeasure method of the view class supports only exactly mode, and if you do not override the Onmeasure method when you customize the control, you can only use exactly mode. The control can correspond to the specific width or match_parent property you specify, and if you want the custom view to support the Wrap_content property, you must override the Onmeasure method, otherwise using wrap_content in the layout is equivalent to using Match_ Parent
2) The measure process of ViewGroup:
For ViewGroup, in addition to completing its own measure process, the measure method of invoking all child elements is traversed, and the individual child elements are recursively executed.
ViewGroup is an abstract class that does not override the view's Onmeasure method, but it provides a Measurechildren method that iterates through the child elements of ViewGroup in the Measurechildren method. The Measurechild method is called and the child element is measure. The idea of Measurechild is to take out the layoutparams of the child elements and then create the measurespec of the child elements through Getchildmeasurespec, Finally, the measurespec of the child element is passed to the measure method to complete the measurement, as shown in:
Figure 5
As mentioned earlier, ViewGroup is an abstract class, it does not rewrite the Onmeasure method, its onmeasure in the measurement process needs its subclasses to implement concretely. such as LinearLayout, Relativelayout. The layout characteristics of different viewgroup subclasses are different, which results in different measurement details.
Here's a quick look at the onmeasure implementation of Linearlyaout and Relativelayout
1) LinearLayout's measure implementation:
There are two layout orientations for LinearLayout, so linearlayout will call measurevertical or measurehorizontal according to Morientation. Take the horizontal layout as an example,
Traverse all view, skip to null or attribute to View.gone, add split line width mdividerwidth and left margin, calculate childwidth and mtotallength of all view, Weight and totalweight of all view are counted, and the pair view is measured.
2) Relativelayout's measure implementation:
After the first execution of onmeasure or requestlayout, you need to call the SortChildren method, sort all the sub-views according to the order of addition, sideways, vertically once, and then examine the two sequences The Getsortedviews method in the dependency graph static class is sorted according to the dependency.
Later in Onmeasure, a pair of view is traversed, that is, two sequences are traversed separately.
The first is a horizontal traverse, call Msortedhorizontalchildren, get relativelayout.layoutparams, call the method in turn, calculate the control's transverse position and mleft and mright, and then measure the sub view horizontally, Then, according to the previous results, I would like to place the child view, if the width of the parent relativelayout is wrap_content at this time, the width of the height will be corrected.
The vertical arrangement of the view sequence after the horizontal is done, the steps are roughly the same, where the sub-view will be measure when the correct measurement, then the action is to the parent relativelayout the width of the higher property to be revised again.
One of the most obvious differences from the above analysis is that Relativelayout needs to traverse two times during the measure process, while linearlayout only needs to traverse the process once.
In addition, it should be noted that, in some extreme cases, the system may need to call multiple measure to determine the final measurement width, in which case the high measurement obtained in the Onmeasure method is likely to be inaccurate. So it's best to get the high width of the view in the OnLayout method.
3. How to get the width and height of the view
(1) Call the Onwindowfocuschanged method (focus change), this time the view has been initialized, this time to get the width of the view is not a problem. However, frequent onresume and onpause,onwindowfocuschanged methods are also frequently called.
(2) Call View.post (runnable)
Post a runnable to the tail of the message queue and wait for Looper to call this runnable,view is also initialized.
(3) Viewtreeobserver
Many callbacks using Viewtreeobserver can use this function, such as Ongloballayoutlistener, when the state of the view tree changes or the visibility of the view tree is changed, Ongloballayoutlistener will be called back, and it is important to note that the Ongloballayoutlistener will be recalled multiple times as the state of the view tree changes.
(4) view.measure (int widthmeasurespec,int heightmeasurespec)
- Match_parent can't
- The specific values and wrap_content can be.
4.Layout process
The layout procedure is used to viewgroup determine the position of the child element, and when the position of the viewgroup is determined, it iterates through all the child elements in the onlayout and calls its layout method, and the OnLayout method is called in the layout method.
The layout method first sets the position of the four vertices of the view through the Setframe method, and then calls the OnLayout method to determine the position of the child elements.
Because the implementation of OnLayout is also related to layout, neither view nor ViewGroup implements the OnLayout method.
5.draw process
- To draw the view to the screen, take a few steps :
1. Draw background Background.draw (canvas)
2. Draw Yourself (OnDraw)
3. Draw Children (Dispatchdraw)
4. Drawing decorations (ondrawscrollbars)
- The drawing of view is done through Dispatchdraw, which iterates through the draw method of all child elements.
- If a view does not need to draw anything, then setting Setwillnotdraw to True will optimize the system, and ViewGroup defaults to True if our custom viewgroup need to be ondraw to draw the content. Need to show off it.
How the Android Learning Note view Works