1. 程式人生 > >Android中設置半個屏幕大小且居中的button布局 (layout_weight屬性)

Android中設置半個屏幕大小且居中的button布局 (layout_weight屬性)

ecc vra sgd oiv red ng2 cdc roi aligned

先看例如以下布局 :

技術分享

上圖中。按鈕的大小為屏幕的一半,然後居中顯示在布局中央,每一個人心中都有自己的答案,看看我的方法吧,布局布局xml例如以下 :

<?

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.將LinearLayout的layout_weight設置為1 --> <!-- 2.將Button的layout_width設為0dp, 而且將layout_weight設置為0.5 --> <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>

這裏有幾個關鍵點:

  1. 布局為LinearLayout,以便能夠設置layout_weight。
  2. 設置LinearLayout的android:weightSum的值為1;
  3. 將Button的layout_width設置為0dp;
  4. 將Button的layout_weight的值設置為0.5。 即上面的android:weightSum的一半。
通過上面的設置就能夠實現上圖中的布局了。

子空間的寬度算法能夠參考例如以下公式, 子控件寬度 = 子控件layout_width + 子控件的layout_weight * 父控件的寬度 / 父控件的layout_weight, 對照上面的樣例就是子控件的寬度 = 0.5 * 父控件的寬度 / 1 = 父控件寬度 * 0.5。 由於父控件的寬度為match_parent,所以父控件寬度的寬度為整個屏幕的寬度,所以子控件的寬度 = 0.5 * 整個屏幕的寬度 = 半屏寬度。



Android中設置半個屏幕大小且居中的button布局 (layout_weight屬性)