<50 the card problem in Android hacks>---custom ViewGroup

Source: Internet
Author: User

The time to learn Android is not short, but has not been seriously read, the previous period of time to see <50 Android Hacks>, I think this book is really good, the domestic also has Chinese version.

Ask to show the above effect, usually I will use relativelayout and layout_margin* to achieve

In this hack, we'll look at another the creating
The same type of layout-we ' ll create a custom view-
Group. The benefits of using a custom ViewGroup
Instead of adding margins by hand in an XML file is
These:

A.It ' s easier to maintain if you ' re using It in different activities.

B. You can use custom attributes to customize the position of the ViewGroup children.
C. The XML'll be easier to understand because it's ll be more concise.
D. If you need-to-change the margins, you won ' t need to recalculate by hand every child ' s margin.



The following is implemented with ViewGroup:

Java:

Package Com.example.lock;import Android.content.context;import Android.content.res.typedarray;import Android.util.attributeset;import android.util.log;import Android.view.view;import android.view.ViewGroup;/** * * @     Author Kutear * */public class Exampleview extends viewgroup{private int horizontal_spacing = 0; private int vertical_spacing = 0;  TypedArray t = Null;public exampleview (context context, AttributeSet Attrs) {Super (context, attrs);//TODO auto-generated Constructor stub//here is get < Exampleview/> Custom Properties t = Context.obtainstyledattributes (Attrs, Com.example.lock.r.styleable.exampleview); horizontal_spacing = T.getdimensionpixelsize (com.example.lock.r.styleable.exampleview_horizontal_spacing, 20); vertical_spacing = T.getdimensionpixelsize (com.example.lock.r.styleable.exampleview_vertical_spacing, 30); int marginleft = t.getdimensionpixelsize (com.example.lock.r.styleable.exampleview_layout_marginleft,10); LOG.V ("Xml-height", "" "+ horizontal_spacing); LOG.V ("Xml-width", ""+ vertical_spacing); LOG.V ("Xml-marginleft", "" "+ marginleft);   T.recycle ();} /** * used to calculate the parent and child dimensions */@Overrideprotected void onmeasure (int widthmeasurespec, int heightmeasurespec) {//TODO auto- Generated method Stubint width = measurespec.getsize (widthmeasurespec); If the width of the fill_parent,viewgroup is the value: int height = measurespec.getsize (heightmeasurespec);//Ibid. log.v ("width", "width:" +width); LOG.V ("height", "Height:" +height); int modewidth = Measurespec.getmode (widthmeasurespec); int modeheight = Measurespec.getmode (HEIGHTMEASURESPEC); LOG.V ("Mode--h:", "" +modeheight); LOG.V ("Mode--w:", "" +modewidth); LOG.V ("At_most:", "" +measurespec.at_most); LOG.V ("Exactly:", "" +measurespec.exactly); LOG.V ("UNSPECIFIED:", "" "+measurespec.unspecified); int childheight = 0; The total height of the child ....  Used to determine ViewGroup is wrap_content when the height int childwidth = 0; ibid. int count = Getchildcount (); for (int i=0;i<count;i++) {View child = Getchildat (i);//this'll display 0LOG.V (" Before-child-size "," "+ child.getmeasuredheight ());//Calculate the size of child MeasuRechild (CHILD,WIDTHMEASURESPEC,HEIGHTMEASURESPEC);//this would display ready sizelog.v ("After-child-size", "" "+ Child.getmeasuredheight ()); Exampleview.layoutparams LP = (exampleview.layoutparams) child.getlayoutparams (); int cheight = Child.getmeasuredheight (); int cwidth = Child.getmeasuredwidth (); if (i==0) {childheight + = Cheight;childwidth + = cWidth+ Lp.marginleft;} else {childheight + = Vertical_spacing;childwidth +=horizontal_spacing+lp.marginleft;}} LOG.V ("Wrap_content:", childwidth+ "---" +childheight); Setmeasureddimension (measurespec.at_most==modewidth?) Childwidth:width,//warp_content when the former measurespec.at_most==modeheight?childheight:height); Parent's Size, fill_parent or wrap_content}/** * Draws the position of child */@Overrideprotected void OnLayout (Boolean changed, int l, I NT T, int r, int b) {/** * parameter means: L-->left ViewGroup's Left coordinate * other similar * ViewGroup in the entire screen position .... * Not viewgroup relative Position ... * * *///TODO auto-generated method stub int wt_s=0; The starting position of the next view//int wt_e=0; End position of Next view intChildCount = Getchildcount ();    LOG.V ("-----", "l=" +l+ "--t=" +t+ "--r=" +r+ "--b=" +b);           for (int i = 0; i < ChildCount; i++) {View Childview = Getchildat (i);           Gets the dimension of the view computed in onmeasure int measureheight = Childview.getmeasuredheight ();           int measuredwidth = Childview.getmeasuredwidth ();        LOG.V ("Child-height", measureheight+ "");        LOG.V ("Child-width", measuredwidth+ "");        Exampleview.layoutparams LP = (exampleview.layoutparams) childview.getlayoutparams ();        LOG.V ("LeftMargin", "+lp.marginleft");        LOG.V ("LeftMargin", "+lp.rightmargin");        wt_s + = (i==0?0:horizontal_spacing) +lp.marginleft;        LOG.V ("wt_s", wt_s+ ""); Here the four-direction parameter bits are relative to the position of the ViewGroup, and the upper-left corner of the ViewGroup (0,0) childview.layout (wt_s, Vertical_spacing*i, Wt_s+measuredwi                    DTH, vertical_spacing*i+measureheight); }} @Override protected Android.view.ViewGroup.LayoutParams generatedefaultlayoutparams () {return new LAyoutparams (ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);        } @Override Public Android.view.ViewGroup.LayoutParams generatelayoutparams (AttributeSet attrs) {    return new Layoutparams (GetContext (), attrs); } @Override protected Android.view.ViewGroup.LayoutParams generatelayoutparams (ANDROID.VIEW.VIEWGROUP.L    Ayoutparams p) {return new Layoutparams (p);         } public static class Layoutparams extends Marginlayoutparams {private int horizontal_spacing = 0;         private int vertical_spacing = 0;        public int marginleft =-1;             Public Layoutparams (Context C, AttributeSet attrs) {super (C, attrs);           TypedArray ta = c.obtainstyledattributes (attrs, R.styleable.exampleview);            Here is the custom attribute obtained in the child in ViewGroup horizontal_spacing = Ta.getint (r.styleable.exampleview_horizontal_spacing,-1); vertical_spacing = Ta. GETINT (R.styleable.exampleview_vertical_spacing,-1);            MarginLeft = ta.getdimensionpixelsize (r.styleable.exampleview_layout_marginleft, 0);            int paddingleft = Ta.getindex (r.styleable.view_paddingend);             LOG.V ("Padding", "+paddingleft");             LOG.V ("MarginLeft", "+marginleft");        Ta.recycle ();        } public layoutparams (int width, int height) {Super (width, height);        } public Layoutparams (Android.view.ViewGroup.LayoutParams source) {super (source);        } public Layoutparams (Marginlayoutparams source) {super (source); }    }}

Xml:

Attrs.xml

<?xml version= "1.0" encoding= "Utf-8"?><resources> <declare-styleable    name= "Exampleview" >        <attr name= "horizontal_spacing" format= "Dimension"/>        <attr name= "vertical_spacing" format= " Dimension "/>        <attr name=" Layout_marginleft "format=" Dimension "/>    </declare-styleable>< /resources>

Test.aml

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/    Android "Xmlns:cascade=" Http://schemas.android.com/apk/res/com.example.lock "android:layout_width=" Match_parent " android:layout_height= "match_parent" android:orientation= "vertical" > <textview android:layout_width= " Match_parent "android:layout_height=" wrap_content "android:text=" Mmmmmm "> </TextView> <co M.example.lock.exampleview android:layout_width= "wrap_content" android:layout_height= "Wrap_content" C ascade:layout_marginleft= "20DP" android:background= "#abcdef" cascade:horizontal_spacing= "30DP" Cascad e:vertical_spacing= "30DP" > <textview android:layout_width= "100DP" Android:layout_heigh t= "150DP" android:background= "#FF0000" android:text= "AAA"/> <textview Andro Id:layout_width= "100DP" android:layout_height= "150DP" cascade:layout_marginleft= "20DP" android:background= "#0000FF" android:text= "BBB"/> <textview android:layout_width= "100DP" android:layout_height= "1 50DP "android:background=" #00FF00 "android:text=" CCC "/> </com.example.lock.ExampleView> </LinearLayout>


<50 the card problem in Android hacks>---custom ViewGroup

Related Article

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.