Android face test summary of Android Advanced (i)
In the previous articles are the basis of speaking, we should feel very familiar with, but often we may not know the basis of some details of the complete or incomplete, I always think that the foundation is relatively difficult, then this chapter finally to the advanced, mainly speaking of the knowledge of the view, in the previous "Android Overview of the interview topic Android Basics (vi)
Already have a certain understanding of the view, because the content is more and is also the interview must question, so will be divided into two articles to continue in-depth understanding of the view.
If you have any questions during the reading process, please do not hesitate to contact us. Please specify Fuchenxuan de Blog if you need to reprint
This chapter is the "Android beauty from 0 to the master of the Road" Android Advanced (a) the process of customizing the view
- Android face test summary of Android advanced one
- Master
- What is view
- Basic concepts of View coordinates
- The life cycle of the view
- Several constructors for View
- Several important methods of View
- Custom View
- Simple comprehension of view drawing
- Categories for Custom View
- Procedures for customizing view
- Custom ViewGroup
- Customizing the ViewGroup process
- Thorough understanding of Measurespec three modes
- Summary of issues
Master
- What is view?
- Basic concepts of View coordinates
- The life cycle of the view
- How to Customize View
What is view?
Android.app.View is the phone's ui,view responsible for drawing the UI, handling events (evnet), Android using View to create the Widgets, using widgets to create an interactive user interface, each View is responsible for a certain area of the drawing.
A diagram to understand common control hierarchy relationships
Basic concepts of View coordinates
The width of the view is determined by the top, left, right, bottom parameters, and X, Y and Translationx, and Translationy is responsible for changing the view position.
Starting with Android3.0, the concept of translation is added, that is, relative to the parent container's offset and the concept of x, y coordinates, X, y represents the horizontal ordinate of the top left vertex. When the view is panning, the getx,gety,setx,sety
get/settranslationx/y to get the coordinates of the current top-left point.
X=left+translationx y in the same vein.
Note: In the process of changing the view, the Top,left equivalent represents the original position and is not changed. Change is only x,y,translationx/y.
A graph that understands the coordinate concept of a view
The life cycle of the view
Category |
Methods |
Description |
Creation |
Constructors |
A few view constructors |
|
Onfinishinflate () |
Call the Onfinishinflate method when the system finishes parsing the view |
Layout |
onmeasure (int, int) |
Determine the size of all child view |
|
OnLayout (boolean, int, int, int, int) |
Triggered when ViewGroup assigns the size and position of all sub-view |
|
onsizechanged (int, int, int, int) |
triggered when the size of the view has changed |
Drawing |
OnDraw (Android.graphics.Canvas) |
Details of the View render content |
Event processing |
OnKeyDown (int, keyevent) |
The button is pressed and then triggered. |
|
onKeyUp (int, keyevent) |
Triggered when the button is pressed and then bounced |
|
Ontrackballevent (motionevent) |
Trackball Events |
|
Ontouchevent (motionevent) |
Touch-screen Events |
Focus |
Onfocuschanged (boolean, int, android.graphics.Rect) |
Triggered when view gets or loses focus |
|
Onwindowfocuschanged (Boolean) |
Triggered when a window contains a view that gets or loses focus |
Attaching |
Onattachedtowindow () |
Triggered when view is attached to a window |
|
Ondetachedfromwindow () |
Triggered when view leaves an attached window, the method and Onattachedtowindow () are the opposite |
|
onwindowvisibilitychanged (int) |
Triggered when the visible view that is contained in the window has changed |
For implementing a custom view, you do not need to override all of these methods. In fact, you can only OnDraw (Android.graphics.Canvas)
Several constructors for View
public MyView(Context context)
When the Java code is directly new to a custom view instance, the first constructor is called
public MyView(Context context, AttributeSet attrs)
Called when the XML is created but no style is specified. More than one parameter of type AttributeSet, custom attribute, when creating a view through the layout file XML, the parameters inside the XML are brought into the view by AttributeSet.
public MyView(Context context, AttributeSet attrs, int defStyleAttr)
The third parameter in the constructor is the default style, where the default style is the default style in the current application or activity theme, and is called only when explicitly called.
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes)
The constructor is added at the time of API21.
Several important methods of View
Requestlayout
View re-calls the layout process
Invalidate
View calls the draw process again
Forcelayout
Identifies the next redraw of the view, which requires a recall of the layout procedure.
Postinvalidate
This method is the same as the Invalidate method, which is to redraw the view tree, but with different conditions of use, postinvalidate is called in a non-UI thread, and invalidate is called in the UI thread.
Custom view simple understanding of the drawing of view
Here we have a simple understanding of the drawing of the view, subsequent articles we will be in-depth understanding.
1. Measurement--onmeasure (): Determines the size of the view
2. Layout--onlayout (): Determines the location of the view in ViewGroup
3. Draw--ondraw (): How to draw this view.
Categories for Custom View
- Inherit view
- Inherit ViewGroup
- Inheriting system controls (Button,linearlayout ...)
Procedures for customizing view
Custom view first implements a class that inherits from view
The constructor of the class is added, typically three construction methods, but the construction method starting from Android5.0 has been added to 4
override
Methods of the parent class, such as onDraw,(onMeasure)
-
Custom properties, you need to create a attrs.xml
file under values, in which you define the properties
By context.obtainstyledattributes the Attrs in the constructor to parse it out, you can get the corresponding property.
TypedArray TypedArray = context.obtainstyledattributes (Attrs, R.styleable.myview);
Mcolor = Typedarray.getcolor (R.styleable.myview_mycolor, 0xff00ff00);
Note Three functions get the difference in size:
getdimension ()
is converted based on the current displaymetrics, Gets the size of the specified resource ID
getdimensionpixelsize ()
and getdimension ()
The function is similar, unlike converting the result to int, and rounding the decimal part
getdimensionpixeloffset ()
and getdimension ()
Functionally similar, the difference is that the result is converted to int, rounding off the decimal. For example
columns such as getdimension ()
return the result is 20.5f, then getdimensionpixelsize ()
Returns the result, getdimensionpixeloffset ()
Returns the result is 20.
Open the layout file we can see a lot of fields that start with xmlns. In fact, this is the abbreviation for XML name space. We can use res-atuo
namespaces instead of adding custom view full class names.
xmlns:app="http://schemas.android.com/apk/res-auto"
/** * Created by Fuchenxuan on 16/6/4. * * Public class MyView extends View { Private intmradius= $;Private intMcolor; Public MyView(Context context) { This(Context,NULL); } Public MyView(context context, AttributeSet attrs) { This(Context, Attrs,0); } Public MyView(context context, AttributeSet attrs,intDEFSTYLEATTR) {Super(Context, attrs, defstyleattr);//read Custom AttrsTypedArray t = context.obtainstyledattributes (attrs, R.styleable.rainbowbar,0,0); Mradius = T.getdimensionpixelsize (R.styleable.coutom_radius, (int) hspace); T.getdimensionpixeloffset (R.STYLEABLE.COUTOM_AT1, (int) vspace); Mcolor=t.getcolor (R.styleable.color, Barcolor); T.recycle ();//We should always recycle after used}@Override protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {//super.onmeasure (Widthmeasurespec, heightmeasurespec); intWidthmode = Measurespec.getmode (Widthmeasurespec);intWidthsize = Measurespec.getsize (Widthmeasurespec);intHeightmode = Measurespec.getmode (Heightmeasurespec);intHeightsize = Measurespec.getsize (Heightmeasurespec);//set sizeSetmeasureddimension (Widthmode = = Measurespec.at_most? (int) Mradius *3: widthsize, Heightmode = = Measurespec.at_most? (int) Mradius *3: Heightsize); }//draw be invoke Clire. intindex =0;@Override protected void OnDraw(Canvas canvas) {//super.ondraw (canvas);Mpaint =NewPaint (); Mpaint.setcolor (Mcolor); Mpaint.setantialias (true); Canvas.drawcircle (Mradius, Mradius, Mradius, Mpaint); }}
Here is a normal custom view, which draws a circle and sets the size of the parent view according to the different modes.
about view rewrite onMeasure()
time :
If it's used wrap_content
. So in the onMeasure()
middle of the call setMeasuredDimension()
,
To specify the width height of the view. If you are using match_parent
or a specific DP value. Then you can use it directly super.onMeasure()
.
Customizing the ViewGroup custom ViewGroup process
- Custom ViewGroup and custom view, just inherit from the ViewGroup class, and must implement the
onLayout()
function
/** * Created by Fuchenxuan on 16-6-6. * * Public class costumviewgroup extends viewgroup { Public Costumviewgroup(Context context) {Super(context); } Public Costumviewgroup(context context, AttributeSet attrs) {Super(context, attrs); }@Override protected void onmeasure(intWidthmeasurespec,intHEIGHTMEASURESPEC) {Super. Onmeasure (Widthmeasurespec, Heightmeasurespec);intChildCount = Getchildcount (); for(inti =0; i < ChildCount; i++) {View Childview = Getchildat (i); Measurechild (Childview, Widthmeasurespec, Heightmeasurespec); } }@Override protected void OnLayout(BooleanChangedintLintTintRintb) {if(changed) {intChildCount = Getchildcount (); for(inti =0; i < ChildCount; i++) {View Childview = Getchildat (i); Childview.layout (i * childview.getmeasuredwidth (),0, (i +1) * Childview.getmeasuredwidth (), Childview.getmeasuredheight ()); } } }}
Here is a simple custom viewgroup that implements similar linearlayout horizontal emission sub view locations. This is a simple viewgroup process.
Thorough understanding of Measurespec three modes
The size of the view is determined not only by itself, but also by the parent control, in order for our control to better adapt to a variety of situations, it will usually measure itself. They are made up of two parts of Mode+size. Widthmeasurespec and Heightmeasurespec are converted into binary numbers, and they are all 30-bit. The first two digits represent mode (measurement mode), and the latter 28 digits are their actual values (size); MeasureSpec.getMode()
Get mode, MeasureSpec.getSize()
get dimensions
The Onmeasure function is used to measure the view size, so we need to know three measurement modes:
EXACTLY
: It is generally set to a definite value (100DP) orMATCH_PARENT
AT_MOST
: Indicates that the child layout is limited to a maximum value, typicallyWARP_CONTENT
UNSPECIFIED
: Indicates how large a sub-layout is to be, seldom used
about ViewGroup rewrite onMeasure()
time :
The first step is to measure the height of the sub-view:
getChildAt(int index)
You can get the Sub view on index.
getChildCount()
Get the number of child view, then loop through the child view.
Measuring methods using the sub view itself
childview.measure (int wspec, int hspec);
or use ViewGroup's method of measuring sub-view :
measureChild(subView, int wSpec, int hSpec);
Measure a sub-view, how wide, how high, and internally add the ViewGroup padding value
measureChildren(int wSpec, int hSpec);
Measure how wide and high all sub-view are, internally calling the Measurechild method
measureChildWithMargins(subView, intwSpec, int wUsed, int hSpec, int hUsed);
Measure a sub-view, how wide, how high, the interior with ViewGroup padding value, margin value and the incoming wide wused, hused
Summary of issues
What is the difference between getwidth () and Getmeasuredwidth ()?
Getmeasuredwidth (): As soon as the Setmeasureddimension () method is executed, it has a value and no longer changes.
GetWidth (): The Onmeasure () must be executed before the value can change.
The value of getwidth () = = Getmeasuredwidth () If OnLayout does not modify the width that the child view actually displays.
What is the difference between onlayout () and layout ()?
OnLayout () ViewGroup a method for the layout of the neutron view, layout () is a method for sub-view layouts
What is the role of Onsavedinstancestate and onrestoreinstancestate in the View?
Like activity, each view has two methods, Onsavedinstancestate and onrestoreinstancestate, that can be used to save and restore the view's state.
In this section we know what is the basic concept of view?,view coordinates, understand the life cycle of the view, and learn how to customize the view? Although it is all theoretical knowledge summary, in the follow-up we will come together to define the view of the actual combat learning. No matter if you have any questions, please leave a message below.
For more questions on Android, please click on the image below.
The level is limited, if have errors and omissions, welcome to correct, criticize, if need reprint, please indicate source –http://blog.csdn.net/vfush, thank you!
Android face test summary of Android Advanced (i)