Set a half screen size and center button layout in Android (Layout_weight property)

Source: Internet
Author: User

let's look at the following layout:


, the button is half the size of the screen, then centered in the center of the layout, everyone has their own answers, see my method, Layout layout XML is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "    android:id=" @+id/main_layout "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "    android:baselinealigned=" false "    android:gravity=" center "    android:orientation=" Horizontal "    android:weightsum=" 1 ">     <!--1. Set the layout_weight of LinearLayout to 1--and    <!--2. Set the Button's layout_width to 0DP and layout_weight to 0.5 and    <button        android:layout_width= "0DP"        android:layout_height= "Wrap_content"        android:layout_weight= "0.5"        android:textsize= "13sp        " android:text= "@string/button_text" >    </Button></LinearLayout>
Here are a few key points:

    1. The layout is linearlayout so that the layout_weight can be set;
    2. Set the value of the LinearLayout android:weightsum to 1;
    3. Set the button's layout_width to 0DP;
    4. Set the value of the button's layout_weight to 0.5, which is half of the android:weightsum above.
you can implement the layout in the above settings. The width of the subspace algorithm can refer to the following formula, child control width = child control layout_width + child control Layout_weight * Parent control's width/parent control's layout_weight, compared to the above example is the width of the child control = 0.5 * The width of the parent control /1 = parent Control width * 0.5, because the width of the parent control is match_parent, so the width of the parent control width is the width of the entire screen, so the width of the child control = 0.5 * Width of the entire screen = half screen width.


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.