LinearLayout 又稱為線性佈局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:text="butotn1"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:text="butotn2"/>
<Button
android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="butotn3"/>
</LinearLayout>
LinearLayout 中通過android:orientation 設定方向,horizontal為水平方向排列(默認),vertical為垂直方向排列。
注意:
如果LinearLayout的排列方式被設定為horizontal,則控件的android:layout_width絕不可以設定為match_parent,如果排列方式被設定為vertical,則控件的android:layout_heigth不可以設定為wrap_content。
android:layout_gravity屬性:用於指定控件在佈局中的對齊方式,android:gravity=”top”(buttom、left、right、center_vertical、fill_vertical、center_horizontal、fill_horizontal、center、fill、clip_vertical、clip_horizontal)指的是控件的文字對其方式。如上例子中的button1 的layout_gravity為top;button2 的layout_gravity為center_vertical,button3的layout_gravity為bottom。
gravity如果需要设置多个属性值,需要使用“|”进行组合
需要注意的是,當LinearLayout 的排列方式設定為horizontal,只有垂直方向上的對齊才會生效,水平方向的長度不固定;
當LinearLayout 的排列方式為vertical,只有水平方向上的對齊才會生效,垂直方向的長度不固定。android:layout_weight屬性:通過比例的方式指定控件的大小。
當控件中有設定layout_weigth,則控件的寬度將不再由layout_width決定。
系統會將LinearLayout中的所有控件指定的layout_weight相加,得到一個總和。然後每個控件所占大小比例就是用這個控件的layout_weight除以總和。
所以假如editText需要佔據屏幕的3/5,button佔據屏幕的2/5,只需要把EditText的layout_weight設定3,button的layout_weight設定為2即可。
以下例子表示button 寬度按wrap_content顯示,editText沾滿剩下的空間。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:id="@+id/editText1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="key in something"
/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button1"
/>
</LinearLayout>
- 3242