How Android Sets the layout center Layout_gravity,layout_margin in code

Source: Internet
Author: User


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

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.