Layout này sắp xếp các View con trong nó theo một chiều, ngang (vertical) hoặc dọc (horizontal) tùy theo giá trị của thuộc tính android:orientation. Linear Layout sẽ tự động sinh ra thanh cuộn nếu kích thước của cửa sổ con vượt quá kích thước màn hình.
Khai báo layout theo chiều dọc:
<LinearLayout android:orientation="vertical"> .... </LinearLayout>
Khai báo layout theo chiều ngang:
<LinearLayout android:orientation="horizontal"> .... </LinearLayout>
Ví dụ về một Linear Layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/LinearLayout1" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <EditText android:id="@+id/txtUsername" android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Username" android:inputType="text" > <requestFocus /> </EditText> <EditText android:id="@+id/txtPassword" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textPassword" android:hint="Password" /> <LinearLayout android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="horizontal" > <Button android:id="@+id/btnLogin" style="?android:attr/buttonStyleSmall" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_weight="1" android:background="#FFD57D" android:gravity="center" android:text="Login" /> <Button android:id="@+id/btnClear" style="?android:attr/buttonStyleSmall" android:layout_width="fill_parent" android:layout_height="wrap_content" android:layout_marginLeft="10dp" android:layout_marginRight="10dp" android:layout_weight="1" android:background="#FF9900" android:gravity="center" android:text="Clear" /> </LinearLayout> <TextView android:id="@+id/lblResult" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Result: " /> </LinearLayout>
Với thiết kế này, chúng ta có kết quả như sau:
Source code của ví dụ minh họa.
[sociallocker id=”444″]Download[/sociallocker]