前些天,在工作中遇到了一個需求:一個“加載上一頁”的按鈕寬度為父控件寬度一半,且水平居中於父控件中。
在此給出兩種思路:
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>