Android单个控件占父控件宽度一半且水平居中

前些天,在工作中遇到了一个需求:一个“加载上一页”的按钮宽度为父控件宽度一半,且水平居中于父控件中。

在此给出两种思路:

1.直接在Activity代码中获取到当前父控件的宽度,并将此按钮宽度值设置成父控件宽度的一半。

2.通过借用LinearLayout的 weightSum 和 layout_weight 属性达到效果。

具体代码如下:

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     android:layout_width="match_parent"
 3     android:layout_height="match_parent"
 4     android:gravity="center_horizontal"
 5     android:orientation="horizontal"
 6     android:weightSum="2" >
 7 
 8     <Button
 9         android:layout_width="0dp"
10         android:layout_height="wrap_content"
11         android:layout_weight="1"
12         android:background="#f00f"
13         android:text="这是一个按钮" >
14     </Button>
15 
16 </LinearLayout>
原文地址:https://www.cnblogs.com/lwbqqyumidi/p/3477708.html