Set the layout in the Code Center, look at the API can know that there are setgravity,setpadding in the view, but there is no direct setlayoutgravity,setmargin and other methods. The following method is implemented in code similar to Layout_gravity,layout_margin in the layout.
can be by setting the view inside; layoutparams settings, and this layoutparams is based on the view in different Groupview and different.
1. Set layout_gravity in code
LinearLayout layouttop= (linearlayout) Findviewbyid (r.id.layout_top); Framelayout.layoutparams params = new Framelayout.layoutparams (Layouttop.getlayoutparams ()); params.gravity = Gravity.center_vertical;layouttop.setlayoutparams (params);
Here the Framelayout, LinearLayout is to explain the view in a framelayout or linearlayout inside, specifically to see their own layout, this place may be error, than in such a mistake. The error is obvious and this is a good solution, just follow the prompts to change the property to the appropriate one.
2. Set layout_margin in code
ImageView image = (ImageView) Findviewbyid (R.id.img_icon); Linearlayout.layoutparams LP = new Linearlayout.layoutparams (Image.getlayoutparams ()); Lp.setmargins (10, 20, 0, 0); IMAGE.SETLAYOUTPARAMS (LP);
The method can be encapsulated as:
public static void SetMargins (view view, int left, int top, int. right, int bottom) {if (View.getlayoutparams () Inst Anceof viewgroup.marginlayoutparams) {viewgroup.marginlayoutparams p = (viewgroup.marginlayoutparams) view.getLa Youtparams (); P.setmargins (left, top, right, bottom); View.requestlayout (); } }
How Android Sets the layout center Layout_gravity,layout_margin in code