This article by Sun Guo Wei original. If you want to reprint, please specify the source!
This article prepares to talk about customizing the ViewGroup. For beginners, the custom viewgroup is the sort of thing that a man of the rank of Daniel can grasp, but he is intimidated.
Don't be afraid, remember "all new things are paper tigers, as long as willing to spend time to study, not learn the things."
Needless to say, next, let's uncover the mystery of custom ViewGroup.
In accordance with the Convention, let's start with an example.
Very simple, 3 cards stacked together to display. How is this layout effect implemented? Some students should say, it is very simple ah, with relativelayout or framelayout, and then for each poker set margin can be achieved.
OK, so take a look at how it's done in this way. The code is as follows:
<relativelayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Fill_ Parent " android:layout_height=" fill_parent "> <view android:layout_width=" 100DP " android: layout_height= "150DP" android:background= "#FF0000"/> <view android:layout_width= "100DP " android:layout_height= "150DP" android:layout_marginleft= "30DP" android:layout_margintop= "20DP" android:background= "#00FF00"/> <view android:layout_width= "100DP" android:layout_height= " 150DP " android:layout_marginleft=" 60DP " android:layout_margintop=" 40DP " android:background=" # 0000FF "/></relativelayout>
Yes, it can be done in this way. But, do not think this way a little low?! Let's do it in a high-level way, and raise your own grid!
Before customizing ViewGroup, we need to understand a few concepts first.
How Android Draws the view
I'm not going to go into too much detail here, but I need to understand some of the words in the Android development documentation:
The drawing layout consists of two traversal processes: the measurement process and the layout process. The measurement process is done by the measure (int, int) method, which traverses the view tree from top to bottom. During recursive traversal, each view passes dimensions and specifications down the layer. When the measure method traversal is complete, each view holds its own size information. The second process is done by the layout (Int,int,int,int) method, which is also the top-down traversal of the view tree, where each parent view locates the location information of all the child views through the results of the measurement process. ”
In short, the first step is to measure the width and height of the ViewGroup, complete in the Onmeasure () method, and ViewGroup traverse all the child views to calculate their size. The second step is to layout all the child views according to the dimensions obtained in the first step, which is done in OnLayout ().
Create Cascadelayout
Finally to the stage of custom ViewGroup. Let's say we've customized a cascadelayout container, and we'll use it this way.
<framelayout xmlns:cascade= "Http://schemas.android.com/apk/res/com.manoel.custom" <!--declaration namespace and Xmlns:an Droid= "Http://schemas.android.com/apk/res/android" android:layout_width= "Fill_parent" android:layout_height= " Fill_parent "> <com.manoel.view.cascadelayout android:layout_width=" fill_parent "Android:layout_hei ght= "Fill_parent" <!--custom Properties--cascade:horizontal_spacing= "30DP" cascade:vertical_spacing= "20 DP "> <view android:layout_width=" 100dp "android:layout_height=" 150DP "Andro id:background= "#FF0000"/> <view android:layout_width= "100DP" android:layout_height= "15 0DP "android:background=" #00FF00 "/> <view android:layout_width=" 100DP "Android oid:layout_height= "150DP" android:background= "#0000FF"/> </com.manoel.view.cascadelayout></fram Elayout>
First, define the properties. Under the Values folder, create a attrs.xml with the following code:
<resources> <declare-styleable name= "Cascadelayout" > <attr name= "Horizontal_spacing" format= "Dimension"/> <attr name= "vertical_spacing" format= "Dimension"/> </declare-styleable ></resources>
Also, for the sake of rigor, define some default vertical and horizontal distances to prevent these attributes from being provided in the layout.
Add the following code to the Dimens.xml:
<resources> <dimen name= "cascade_horizontal_spacing" >10dp</dimen> <dimen name= " Cascade_vertical_spacing ">10dp</dimen></resources>
Preparation work has been done, next look at the source of Cascadelayout, a little bit long, back to help you analyze.
public class Cascadelayout extends ViewGroup {private int mhorizontalspacing; private int mverticalspacing; Public Cascadelayout (context context, AttributeSet Attrs) {Super (context, attrs); TypedArray a = Context.obtainstyledattributes (Attrs, r.styleable.cascadelayout); try {mhorizontalspacing = A.getdimensionpixelsize (r.styleable.cascadelayout_horizontal_spacing, G Etresources (). Getdimensionpixelsize (r.dimen.cascade_horizontal_spacing)); mverticalspacing = A.getdimensionpixelsize (r.styleable.cascadelayout_vertical_spacing, GetResources () . Getdimensionpixelsize (r.dimen.cascade_vertical_spacing)); } finally {a.recycle (); }} @Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int width = getpaddingleft (); int height = getpaddingtop (); int verticalspacing; Final int count = Getchildcount (); for (int i = 0; i < count; i++) {Verticalspacing = mverticalspacing; View child = Getchildat (i); Measurechild (Child, Widthmeasurespec, Heightmeasurespec); Layoutparams LP = (layoutparams) child.getlayoutparams (); width = getpaddingleft () + mhorizontalspacing * i; lp.x = width; lp.y = height; if (lp.verticalspacing >= 0) {verticalspacing = lp.verticalspacing; } width + = Child.getmeasuredwidth (); Height + = verticalspacing; } width + = Getpaddingright (); Height + = Getchildat (Getchildcount ()-1). Getmeasuredheight () + Getpaddingbottom (); Setmeasureddimension (resolvesize (width, widthmeasurespec), resolvesize (height, heightmeasurespec)); } @Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) {Final int count = Getchildcount (); for (int i = 0; i < count; i++) {View child = Getchildat (i); Layoutparams LP = (layoutparams) child.getlayoutparams (); Child.layout (lp.x, lp.y, lp.x + Child.getmeasuredwidtH (), Lp.y + child.getmeasuredheight ()); }} @Override protected Boolean checklayoutparams (Viewgroup.layoutparams p) {return P instanceof layoutparams; } @Override protected Layoutparams generatedefaultlayoutparams () {return new Layoutparams (Layoutparams.wrap_content, Layoutparams.wrap_content); } @Override Public Layoutparams generatelayoutparams (AttributeSet attrs) {return new Layoutparams (GetContext (), attr s); } @Override protected Layoutparams generatelayoutparams (Viewgroup.layoutparams p) {return new Layoutparams (P.width, P.height); } public static class Layoutparams extends Viewgroup.layoutparams {int x; int y; public int verticalspacing; Public Layoutparams (context context, AttributeSet Attrs) {Super (context, attrs); } public Layoutparams (int w, int h) {super (W, h); } }}
First, the constructor is parsed.
Public Cascadelayout (context context, AttributeSet Attrs) { Super (context, attrs); TypedArray a = Context.obtainstyledattributes (Attrs, r.styleable.cascadelayout); try { mhorizontalspacing = a.getdimensionpixelsize ( r.styleable.cascadelayout_horizontal_spacing, Getresources (). Getdimensionpixelsize ( r.dimen.cascade_horizontal_spacing)); mverticalspacing = A.getdimensionpixelsize ( r.styleable.cascadelayout_vertical_spacing, getResources () . Getdimensionpixelsize (r.dimen.cascade_vertical_spacing)); } finally { a.recycle (); } }
If you use Casecadelayout in a layout, the system calls this constructor, which everyone should know. Why is not explained here, interested can go to see the source code, the focus of the system is how to parse the XML layout.
The constructor is simple, which is to get the horizontal and vertical distances from the properties in the layout file.
Then, analyze your custom layoutparams.
The purpose of this class is to save the x, Y axis position of each child view. This defines it as a static inner class. PS: Refers to the static internal class, I think of the problem of multi-threaded memory leaks, if you have time to explain the multi-threaded memory leaks.
public static class Layoutparams extends Viewgroup.layoutparams { int x; int y; public int verticalspacing; Public Layoutparams (context context, AttributeSet Attrs) { Super (context, attrs); } Public Layoutparams (int w, int h) { super (W, h); } }
In addition, some methods need to be rewritten, checklayoutparams (), generatedefaultlayoutparams (), etc., which are often the same between different viewgroup.
Next, analyze the Onmeasure () method.
@Override protected void onmeasure (int widthmeasurespec, int heightmeasurespec) {int width = getpaddingleft (); int height = getpaddingtop (); int verticalspacing; Final int count = Getchildcount (); for (int i = 0; i < count; i++) {verticalspacing = mverticalspacing; View child = Getchildat (i); Measurechild (Child, Widthmeasurespec, Heightmeasurespec); Make each sub-view measure itself layoutparams LP = (layoutparams) child.getlayoutparams (); width = getpaddingleft () + mhorizontalspacing * i; Save x, y axis coordinates for each sub-view lp.x = width; lp.y = height; if (lp.verticalspacing >= 0) {verticalspacing = lp.verticalspacing; } width + = Child.getmeasuredwidth (); Height + = verticalspacing; } width + = Getpaddingright (); Height + = Getchildat (Getchildcount ()-1). Getmeasuredheight () + Getpaddingbottom (); Use the calculated width and height to set the measurement size of the entire layout setmeasureddimension (resolvesize (width, widthmeasurespec), resolvesize (height, heighTMEASURESPEC)); }
Finally, the OnLayout () method is analyzed.
@Override protected void OnLayout (Boolean changed, int l, int t, int r, int b) { final int count = Getchildcount () ; for (int i = 0; i < count; i++) { View child = Getchildat (i); Layoutparams LP = (layoutparams) child.getlayoutparams (); Child.layout (lp.x, lp.y, lp.x + child.getmeasuredwidth (), lp.y + child.getmeasuredheight ()); } }
The logic is simple, and the value computed with the Onmeasure () method loops through the layout () method of the child view for the parameter loop.
To add a custom property to a child view
As an example, the following adds a child view to override the vertical spacing method.
The first step is to add a new property to the Attrs.xml.
<declare-styleable name= "Cascadelayout_layoutparams" > <attr name= "layout_vertical_spacing" format= " Dimension "/> </declare-styleable>
The property name here is Layout_vertical_spacing, because the property name prefix is layout_ and not the view intrinsic property, so the property is added to the Layoutparams property sheet. Read this new property in the constructor of the Cascadelayout class.
public static class Layoutparams extends Viewgroup.layoutparams { int x; int y; public int verticalspacing; Public Layoutparams (context context, AttributeSet Attrs) { Super (context, attrs); TypedArray a = Context.obtainstyledattributes (Attrs, r.styleable.cascadelayout_layoutparams); try { verticalspacing = a . Getdimensionpixelsize ( r.styleable.cascadelayout_layoutparams_layout_ Vertical_spacing, -1); } finally { a.recycle (); } } Public Layoutparams (int w, int h) { super (W, h); } }
So how do you use this property? So easy!
<com.manoel.view.cascadelayout android:layout_width= "fill_parent" android:layout_height= "Fill_ Parent " cascade:horizontal_spacing=" 30DP " cascade:vertical_spacing=" 20DP "> <!--note: This" poker card " Used layout_vertical_spacing Properties-- <view android:layout_width= "100DP" android:layout_height= " 150DP " cascade:layout_vertical_spacing=" 90DP " android:background=" #FF0000 "/> <view Android:layout_width= "100DP" android:layout_height= "150DP" android:background= "#00FF00"/> <view android:layout_width= "100DP" android:layout_height= "150DP" android:background= "#0000FF "/> </com.manoel.view.CascadeLayout>
Resources
Http://developer.android.com/guide/topics/ui/how-android-draws.html
Http://developer.android.com/reference/android/view/ViewGroup.html
Http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html
Postscript
This is all the content of this article. You should have a perceptual understanding of how to customize ViewGroup.
If you want to master custom ViewGroup, there is only one way, that is, multi-brain, diligent hands!
Well, to say so much, if there is any problem, despite the message, we communicate together, progress together! Together to enhance the grid, together to do the UI great God!
Android Development Tips-How to customize ViewGroup