在布局檔案activity_main.xml,在預設添加的垂直線性布局管理器 < LinearLayout>中添加兩個嵌套的< LinearLayout>,然後設定第一個 < LinearLayout>的排列方式為水準排列,在其中添加4個水準并排的TextView元件,并分别設定TextView元件文本的對齊方式,設定第二個< LinearLayout>的排列方式為垂直排列,并在其中添加4個垂直排列的TextView元件。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.shenfan.linearlayout.MainActivity">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="紅色"
android:gravity="center"
android:background="#aa0000"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="藍色"
android:gravity="top|center"
android:background="#0000aa"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="黃色"
android:gravity="bottom|center"
android:background="#aaaa00"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="綠色"
android:gravity="fill_vertical"
android:background="#00aa00"
android:layout_weight="1"
/>
</LinearLayout>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight = "1"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="第一行"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="第二行"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="第三行"
android:layout_weight="1"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="第四行"
android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
運作界面如下圖: