Q: How do I place a Button in the middle of the layout and set its width to 50% of its parent?
Analysis: The problem should be as follows:
(Original address: http://blog.csdn.net/vector_yi/article/details/24397733)
This may seem difficult, but many developers do not know the best way to achieve this effect.
Solution: here we use the weightSum attribute together with the layout_weight attribute.
<LinearLayout xmlns: android = "http://schemas.android.com/apk/res/android" android: layout_width = "fill_parent" android: layout_height = "fill_parent" android: background = "# ffffff" android: gravity = "center" android: orientation = "horizontal" android: weightSum = "1"> <! -- 1. Add the android: weightSum Property --> <Button android: layout_width = "0dp" <! -- 2. Set the layout_width of the Button to 0dp --> android: layout_height = "wrap_content" android: layout_weight = "0.5" <! -- 3. Make sure that it occupies 50% of the available space --> android: text = "@ string/activity_main_click_me"/> </LinearLayout>
It can be noted that the layout_width of the Button is set to 0dp in step 1, will it conflict with layout_weight? The answer is no: the width of a Widget is calculated as follows: Widget's width + Widget's weight * Parent's width/Parent's weightSum