編輯:Android 開發實例
做 App 就像裝修房子:先想清楚要擺哪些家具(控制項),再決定怎麼擺(佈局)。Android 把「怎麼擺」這件事交給了 Layout 類來負責,它管理著子控制項在螢幕上的位置與大小。好消息是,官方只提供了幾個非常樸素的佈局模型,把它們靈活嵌套組合,就足以拼出絕大多數我們想要的介面。
本文用一個小程式的形式,把五種常見佈局逐一跑一遍:主介面用一個 ListView 列出各個佈局入口,點哪一項就跳去對應的展示頁。這樣比單看規範文件直觀得多。
這是我們日常開發中出現頻率最高的一種佈局。核心只有一個屬性:android:orientation,設成 vertical 就縱向堆疊,設成 horizontal 就橫向排隊。下面是一個典型的登入介面:標題在上,帳號與密碼各佔一行,按鈕靠右。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingTop="20dip"
android:paddingBottom="20dip"
android:text="Admin Login"
android:textColor="@color/blue"
android:textStyle="bold" />
<LinearLayout
android:id="@+id/layout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingBottom="20dip">
<TextView
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minWidth="80dip"
android:text="Name" />
<EditText
android:id="@+id/edtName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minWidth="120dip" />
</LinearLayout>
<LinearLayout
android:id="@+id/layout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="@+id/txtPsw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:minWidth="80dip"
android:text="password" />
<EditText
android:id="@+id/edtPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minWidth="120dip" />
</LinearLayout>
<LinearLayout
android:id="@+id/layout3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right">
<Button
android:id="@+id/btnOk"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="70dip"
android:text="O K" />
<Button
android:id="@+id/btnCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="70dip"
android:text="Cancel" />
</LinearLayout>
</LinearLayout>
仔細看會發現:外層是縱向的 LinearLayout,裡面又嵌了三個橫向的 LinearLayout,分別負責標題、帳號列、密碼列與按鈕列。線性佈局真正的威力來自嵌套,單層永遠排不出來的效果,兩三層組合往往就出來了。
寫過 .NET WinForm 的朋友對這種模式應該很親切:控制項落在父容器的哪個位置,完全由它的橫縱座標決定。Android 中用 android:layout_x 和 android:layout_y 來指定,座標系原點在左上角,向右為 x 正方向,向下為 y 正方向。
下面的例子用左右方向鍵控制一個小人左右走動,順便示範如何用絕對佈局擺放元素:
<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/AbsoluteLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/txtIntro"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="20dip"
android:layout_y="20dip"
android:text="按左右鍵控制小人運動" />
<ImageView
android:id="@+id/imgMan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="100dip"
android:layout_y="100dip" />
</AbsoluteLayout>
移動與換圖的邏輯寫在 Activity 裡,重點是兩個:一是用枚舉記錄小人目前的狀態(站立、向左跑、向左停、向右跑、向右停),二是每次按鍵都重新呼叫 layout() 改寫座標,同時換掉背景圖。
package cnblogs.com.layout;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.ImageView;
public class AbsoluteLayoutActivity extends Activity {
private ImageView man;
// 用枚舉描述小人的動作狀態
public enum ManState {
Stand, LeftRun, LeftStop, RightRun, RightStop
}
private ManState curState = ManState.Stand;
private int dx;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.absolute);
man = (ImageView) findViewById(R.id.imgMan);
man.setBackgroundResource(R.drawable.manstand);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = super.onKeyDown(keyCode, event);
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT:
// 在「跑」與「停」兩張圖之間切換,形成走路的錯覺
if (curState == ManState.LeftRun) {
curState = ManState.LeftStop;
man.setBackgroundResource(R.drawable.manleftstop);
} else if (curState == ManState.LeftStop) {
curState = ManState.LeftRun;
man.setBackgroundResource(R.drawable.manleftrun);
} else {
curState = ManState.LeftRun;
man.setBackgroundResource(R.drawable.manleftrun);
}
// 左邊撞牆檢測
dx = man.getLeft() - 1 > 0 ? man.getLeft() - 1 : 0;
man.layout(dx, man.getTop(),
dx + Math.abs(man.getWidth()),
man.getTop() + Math.abs(man.getHeight()));
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (curState == ManState.RightRun) {
curState = ManState.RightStop;
man.setBackgroundResource(R.drawable.manrightstop);
} else if (curState == ManState.RightStop) {
curState = ManState.RightRun;
man.setBackgroundResource(R.drawable.manrightrun);
} else {
curState = ManState.RightRun;
man.setBackgroundResource(R.drawable.manrightrun);
}
// 右邊撞牆檢測,超出範圍就貼在螢幕右緣
dx = man.getLeft() + 1 < 360 - man.getWidth()
? man.getLeft() + 1
: man.getDisplayWidth() - man.getWidth();
man.layout(dx, man.getTop(),
dx + Math.abs(man.getWidth()),
man.getTop() + Math.abs(man.getHeight()));
break;
default:
break;
}
return ret;
}
}
這個小例子也順手回答了一個常見問題:怎麼做逐幀動畫?其中一種土辦法就是持續改寫控制項的座標,再按節奏替換背景圖。缺點也很明顯——座標寫死、不同解析度要各自調參,所以官方後來明確不建議使用 AbsoluteLayout。
TableLayout 以「行 × 列」的方式管理子控制項:每一行就是一個 TableRow 物件,往 TableRow 裡每丟一個控制項,就相当于多出一欄。它最有意思的地方在於三個控制欄寬的屬性:
android:collapseColumns:隱藏指定序號的列(序號從 0 開始)android:stretchColumns:讓指定列可伸展,內容太長時會把後面的列擠出可視區域android:shrinkColumns:讓指定列可收縮,空間不足時優先壓縮它下面這個例子用四個 TableLayout 把三種行為加「完全不設定」的對照組一次展示完:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- 隱藏第 2、3、4 列 -->
<TableLayout
android:id="@+id/table1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:collapseColumns="1,2,3">
<TextView
android:id="@+id/txt1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Table1" />
<TableRow>
<TextView android:text="col0" />
<TextView android:text="col1" />
<TextView android:text="col2" />
<TextView android:text="col3" />
</TableRow>
</TableLayout>
<!-- 第 2 列可伸展 -->
<TableLayout
android:id="@+id/table2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="1">
<TextView
android:id="@+id/txt2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Table2" />
<TableRow>
<TextView android:text="col0" />
<TextView android:text="col1" />
<TextView android:text="col2" />
<TextView android:text="col3" />
</TableRow>
</TableLayout>
<!-- 第 1 列可收縮,塞長文字也不撐破畫面 -->
<TableLayout
android:id="@+id/table3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:shrinkColumns="0">
<TextView
android:id="@+id/txt3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Table3" />
<TableRow>
<TextView android:text="welcome to world of android" />
<TextView android:text="col1" />
<TextView android:text="col2" />
<TextView android:text="col3" />
</TableRow>
</TableLayout>
<!-- 完全不設定,既不伸展也不收縮 -->
<TableLayout
android:id="@+id/table4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:id="@+id/txt4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Table4" />
<TableRow>
<TextView android:text="col0" />
<TextView android:text="this column will be very long" />
<TextView android:text="col2" />
<TextView android:text="col3" />
</TableRow>
</TableLayout>
</LinearLayout>
最外層是一個縱向 LinearLayout,裡面並排四個 TableLayout,正好構成一組對照實驗:隱藏、伸展、收縮、放任不管。跑一次就能把這三個屬性的效果記牢。
RelativeLayout 的思路是「以別人為參照」:控制項可以相對於父容器對齊(如 layout_alignParentRight),也可以相對於某個兄弟控制項定位(如 layout_toRightOf="@id/name")。它不需要多層嵌套就能做出左右分欄、上下貼齊的效果,效能上也比嵌套 LinearLayout 更划算,是現代 Android 介面裡非常常用的一種。
FrameLayout 是最簡單的一種:所有子控制項都堆在同一個位置,像一疊紙片。點擊 FrameLayout 選項會看到下面這個效果。
看起來有點怪異,因為它是用兩個 ImageView 把兩張圖疊在一起——一件 T-shirt 當底圖,上面蓋一顆頭像。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/FrameLayout01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/shirt" />
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="100dip"
android:paddingTop="18dip"
android:src="@drawable/head1" />
</FrameLayout>
這裡有一條一定要記住的規則:在 FrameLayout 中,後加入的子控制項會蓋在先加入的上面。第二個 ImageView 用 padding 把自己往右下推了一點,於是就疊出了「人穿上衣服」的錯覺。這個特性也常被拿來做圖片浮層、 loading 遮罩、按鈕與角標疊放等效果。
五種佈局沒有優劣,只有適用場景:單純排隊用 LinearLayout;需要精確座標的舊場景用 AbsoluteLayout(新專案請改用 FrameLayout、RelativeLayout 或 ConstraintLayout);表格資料用 TableLayout;講究層級扁平與靈活對齊用 RelativeLayout;需要層層覆蓋用 FrameLayout。把它們當積木, Two 三層組合起來,幾乎沒有排不出來的介面。
Android 基礎:Fragment 與 Activity 互動詳解
本文繼續探討 Fragment 元件的特性,重點在於它與 Activity 的互動以及生命週期的關係。由於 Fragment 依賴於 Activity,兩者的生命週期緊密
Android 記事本示例剖析(四):NoteEditor 類與 Content Provider 機制
在前一篇中,我們研究了 Activity 的生命週期、狀態轉換機制以及自定義控件。本文延續記事本示例的分析,重點拆解 NoteEditor 類與 Content Prov
ExpandableListView 實作三層樹形菜單的兩個關鍵難題
Android 上做樹形菜單,標準武器是 ExpandableListView,也有人自己繼承 ListView 或 LinearLayout 硬刻。但 Expandab
用 JSONArray 與 JSONObject 拆解 Android 的 JSON 資料
行動裝置上的資料多半來自遠端 API,而 JSON 正是這些回應最常見的樣貌。相比 XML,它少了標籤的冗餘,寫起來省事、讀起來清楚,解析速度也更快。本章要帶你看懂一份