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

时间:2023-03-09 22:30:20
Android单个控件占父控件宽度一半且水平居中

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

在此给出两种思路:

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

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

具体代码如下:

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal"
android:weightSum="2" > <Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#f00f"
android:text="这是一个按钮" >
</Button> </LinearLayout>