比例分配

  • android:layout_weight
    1. 子元件或子框架的比重。
    2. LinearLayout 下的子元件或子框架,才能設定這項屬性。
    3. 將要設定比重之方向的元件或框架的長度設為0px或是0dp。

範例:等比例分配

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:layout_weight="1"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:layout_weight="1"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 3"
        android:layout_weight="1"/>

</LinearLayout>
  • 將比重皆設為1,所以大小相同。

範例:非等比例分配1

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal">

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:layout_weight=".10"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:layout_weight=".20"/>

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 3"
        android:layout_weight=".70"/>

</LinearLayout>
  • ".10" 即為 0.1 也即為10 %

範例:非等比例分配2

<LinearLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 1"
        android:layout_weight="1" />

    <Button
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:text="Button 2"
        android:layout_weight="2" />

</LinearLayout>
  • 這樣設定即會按照比重,1的部分為1/(1+2),2的部分為2/(1+2)。