編輯:關於 Android 程式設計
前面我們已經對 Android 程式的執行原理與佈局檔有了基本認識,也用「Hello World!」驗證過一次。在往下深入之前,有個該補的基礎得先補完:View 的幾種佈局顯示方式。把這塊弄懂,之後寫畫面就不必再反覆糾結排版問題。
本文會逐一實作七種常見佈局:線性佈局、相對佈局、表格佈局、列表視圖、網格視圖、絕對佈局與標籤佈局,中間還會穿插 layout_weight、Adapter 分類、Tab 的經典空指標例外等實務眉角。
在 Android 中,使用者介面是由 View 與 ViewGroup 物件堆疊出來的。View 是畫面上最基本的元件單位,而 ViewGroup 則是「佈局」與「檢視容器」的基底類別,同時定義了 ViewGroup.LayoutParams 作為子元件佈局參數的依據——它決定了子 View 希望以什麼方式呈現,例如 XML 中那些 layout_something 屬性。
我們要介紹的七種佈局,全都是直接或間接繼承自 ViewGroup。實際上,所有佈局都可以歸類為 ViewGroup 的五個直接子類,其他佈局多半是這五類的延伸:

圖 1、繼承自 ViewGroup 的一些佈局類
線性佈局會把子元件排成一條線,方向由 android:orientation 決定:horizontal 為水平、vertical 為垂直。最簡單的寫法如下(res/layout/main.xml):
<?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="fill_parent"
android:orientation="horizontal"><!-- 注意這裡 -->
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button1" android:layout_weight="1" />
<Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button2" android:layout_weight="1" />
<Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button3" android:layout_weight="1" />
<Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button4" android:layout_weight="1" />
<Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button5" android:layout_weight="1" />
</LinearLayout>
根節點是一個 LinearLayout,底下五顆 Button 水平排列,執行結果如下:

圖 2、線性佈局(水平)
把 orientation 改成 vertical,就變成縱向排列:

圖 3、線性佈局(垂直)
這個屬性非常關鍵,不寫的話預設值為 0。把上面水平佈局中的 weight 全部移除,結果會變成這樣:

圖 4、layout_weight 屬性的影響
明明寫了五顆按鈕,卻只顯示兩顆,原因就在這裡。weight 顧名思義是「權重」,用來標示同一個線性佈局中各子 View 的重要程度,預設為 0,代表「我需要多大空間就佔多大」。五顆 Button 的寬高都是 wrap_content,又都沒有設 weight,於是 Button1、Button2 光靠文字內容就把整條寬度吃光,後面三顆自然被擠到看不見的地方。
一旦給了 0 以上的值,父容器剩下的空間就會依各子 View 的 weight 比例來切分。舉例來說,若一個水平佈局裡有一個文字標籤和兩個輸入框:標籤沒設 weight,只佔它需要的最小空間;兩個輸入框都設 1,就平分剩下的寬度;若第一個設 1、第二個設 2,則剩餘空間的三分之二給第一個、三分之一給第二個(數值越小,佔到的空間越多)。
相對佈局以「相對位置」安排子 View:一個元件可以相對於兄弟元件定位(例如在另一個元件的左邊或下方),也可以相對於父容器的特定區域定位(例如靠右對齊、置中偏左)。
它是設計介面時相當有力的工具,因為能消除不必要的巢狀結構。如果你發現自己已經套了好幾層 LinearLayout,就是該考慮改用 RelativeLayout 的時候了。
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Type here:" />
<EditText
android:id="@+id/entry"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@android:drawable/editbox_background"
android:layout_below="@id/label" /><!-- 注意這裡 -->
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dip"
android:text="OK" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>
這份佈局包含一個 TextView、一個 EditText 與兩顆 Button。真正在做定位的是那幾個標記出來的屬性:layout_below、layout_alignParentRight、layout_toLeftOf、layout_alignTop 等等,屬性值填的是參照對象的 id。這些屬性名幾乎是英文直譯,看字面就能理解,不再逐一解釋。(提醒:實際執行時要把示範用的註解清乾淨,避免 XML 解析出錯。)

圖 5、相對佈局
表格佈局以「列與欄」的方式標示子 View 的位置,概念與 HTML 的 table 幾乎一致,其中 TableRow 就相當於 HTML 的 <tr>。
使用時有三個常用屬性:
android:shrinkColumns(對應 setShrinkAllColumns(boolean)):讓指定列的內容收縮以適應螢幕,不會被擠出畫面。列號從 0 開始,多列以逗號分隔,例如 android:shrinkColumns="0,1,2"。android:collapseColumns(對應 setColumnCollapsed(int, boolean)):隱藏指定的列。android:stretchColumns(對應 setStretchAllColumns(boolean)):讓指定的列拉伸填滿剩餘空間。
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:shrinkColumns="0,1,2"><!-- 注意這裡 -->
<TableRow><!-- row1 -->
<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button1" android:layout_column="0" />
<Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button2" android:layout_column="1" />
</TableRow>
<TableRow><!-- row2 -->
<Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button3" android:layout_column="1" />
<Button android:id="@+id/button4" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button4" android:layout_column="1" />
</TableRow>
<TableRow>
<Button android:id="@+id/button5" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello, I am a Button5" android:layout_column="2" />
</TableRow>
</TableLayout>

圖 6、表格佈局
列表佈局以可滾動的清單呈現子 View,元素由 ListAdapter 自動插入。ListAdapter 繼承自 Adapter,是 ListView 與資料來源之間的橋樑,能顯示任何包裝在它裡面的資料。它有兩個重要的抽象方法:
public abstract boolean areAllItemsEnabled():ListAdapter 中的所有元素是否都可用?回傳 true 代表全部可點擊。public abstract boolean isEnabled(int position):指定位置的元素是否可用?下面做一個可滾動清單,資料來自字串陣列,點擊項目時用 Toast 顯示該項目。
1)先把 res/layout/main.xml 改成單純的項目佈局:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
2)接著是程式碼:
package skynet.com.cnblogs.www;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
public class HelloWorld extends ListActivity {
// 注意:這裡繼承的是 ListActivity,不是 Activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.main, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 點擊時用 Toast 顯示該項目文字
Toast.makeText(getApplicationContext(),
((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
static final String[] COUNTRIES = new String[] {
"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12",
"13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"
};
}
Note:這裡不像一般 Activity 那樣用 setContentView() 載入佈局,而是用 setListAdapter(ListAdapter) 讓 ListActivity 自動補上一個填滿整個螢幕的 ListView。ArrayAdapter 的三個參數分別是:context(這裡是 this)、項目佈局(R.layout.main)、要塞進清單的陣列(COUNTRIES)。
setOnItemClickListener() 註冊了點擊監聽器,使用者點項目時 onItemClick() 被觸發,這裡就跳出一個 Toast。
3)執行結果(點了「1」之後下方顯示 1):

圖 7、列表佈局
NOTE:把類別從 Activity 改成 ListActivity 之後,若執行時出現「Conversion to Dalvik format failed with error 1」,解法是 Project → Clean... → 勾選專案 → Ok,讓工具重新產生一次 class 檔即可。
上面把清單內容硬寫在 Java 裡,缺乏彈性,也不符合「介面與行為分離」的原則。更好的做法是把資料放進 res/values/strings.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="countries_array">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
<item>6</item>
<item>7</item>
</string-array>
</resources>
程式碼側改成動態讀取:
String[] countries = getResources().getStringArray(R.array.countries_array); setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, countries));
列表佈局的關鍵只有三件事:
依資料來源不同,Adapter 主要分三類:
String[] → ArrayAdapterList<Map<String, ?>> → SimpleAdapterArrayAdapter 顧名思義就是把資料放進陣列,上面的例子就是這種;SimpleAdapter 彈性最大,可以自訂項目佈局,放 ImageView、Button、CheckBox 都沒問題;SimpleCursorAdapter 則是與資料庫搭配使用。篇幅關係,後兩種這裡不另外實作。
網格佈局以二維、可滾動的網格呈現子 View,元素同樣由 ListAdapter 插入,用法與列表佈局相同,這裡不重複說明。
下面實作一個顯示縮圖的網格,點擊項目時顯示位置。
1)先準備幾張圖片放進 res/drawable/。
2)res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />
屬性名稱都很好懂:欄寬、欄數自動、水平與垂直間距、縮放模式與置中對齊。
3)onCreate() 部分:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(HelloWorld.this, " " + position, Toast.LENGTH_SHORT).show();
}
});
}
4)自訂的 ImageAdapter:
package skynet.com.cnblogs.www;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// 為每個項目建立 ImageView,並善用 convertView 回收
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// 圖片資源
private Integer[] mThumbIds = {
R.drawable.linearlayout1,
R.drawable.linearlayout2,
R.drawable.linearlayout3,
R.drawable.listview,
R.drawable.relativelayout,
R.drawable.tablelayout
};
}
ImageAdapter 繼承 BaseAdapter,因此必須實作它要求的幾個方法。建構子與 getCount() 很好理解;getItem() 應該回傳該位置的實際物件、getItemId() 應該回傳列號,但這個範例用不到,回傳 null 與 0 即可。
重點在 getView():它為每個要顯示的圖片建立 View。由於 ListView/GridView 會回收 View,所以必須先判斷 convertView 是否為 null。為空的話就 new 一個 ImageView 並設定顯示屬性:
setLayoutParams(ViewGroup.LayoutParams):固定寬高,確保不管原圖多大,都會被縮放剪裁成一致尺寸。setScaleType(ImageView.ScaleType):指定向中心剪裁。setPadding(int, int, int, int):設定間距;若圖片長寬比差異大,較小的 padding 會導致更多剪裁。如果 convertView 不為 null,就直接複用並重新設定圖片即可。最後把 position 傳給 setImageResource() 從 mThumbIds 中取出對應資源。
執行結果(點了第一張圖之後):

圖 8、網格佈局
絕對佈局以座標定位子 View,直接在佈局檔或程式碼中指定 x、y 即可。
<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:text="絕對佈局"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_x="20dip"<!-- 注意這裡 -->
android:layout_y="20dip"><!-- 注意這裡 -->
</TextView>
</AbsoluteLayout>
概念很直觀,但實務上並不推薦:一旦螢幕尺寸或密度改變,寫死的座標很容易跑掉。它已被標記為 deprecated,僅適合極少數需要精確定位的場合。
標籤佈局以分頁方式呈現子 View,就像瀏覽器在一個視窗裡切換多個網頁那樣。
要建立分頁 UI 需要 TabHost 與 TabWidget。TabHost 必須是佈局的根節點,內部包含負責繪製分頁的 TabWidget,以及負責顯示內容的 FrameLayout。
分頁內容有兩種實作方式:在同一個 Activity 中交換 View,或在各自獨立的 Activity 之間切換。若每個分頁提供的是不同功能,建議用獨立 Activity,較好管理。下面用獨立 Activity 的做法示範。
1)建立三個 Activity:ArtistsActivity、AlbumsActivity、SongsActivity,各自顯示一段文字:
public class ArtistsActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textview = new TextView(this);
textview.setText("This is the Artists tab");
setContentView(textview);
}
}
另外兩個類別寫法相同。
2)準備分頁圖示。每個圖示要有兩個版本:選中與未選中。慣例是選中時用深色(灰)、未選中用淺色(白)。接著用 state-list drawable 描述狀態對應關係,新增 res/drawable/ic_tab_artists.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="https://schemas.android.com/apk/res/android">
<!-- 選中時使用灰色 -->
<item android:drawable="@drawable/ic_tab_artists_grey" android:state_selected="true" />
<!-- 未選中時使用白色 -->
<item android:drawable="@drawable/ic_tab_artists_white" />
</selector>
3)res/layout/main.xml:
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="https://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="5dp" />
</LinearLayout>
</TabHost>
TabHost 內部必須同時有 TabWidget 與 FrameLayout,兩者以垂直線性方式排列。
4)HelloWorld.java:
package skynet.com.cnblogs.www;
import android.widget.TabHost;
import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
public class HelloWorld extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Resources res = getResources();
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
// 每個分頁用一個 Intent 啟動對應的 Activity
intent = new Intent().setClass(this, ArtistsActivity.class);
spec = tabHost.newTabSpec("artists")
.setIndicator("Artists", res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, AlbumsActivity.class);
spec = tabHost.newTabSpec("albums")
.setIndicator("Albums", res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
intent = new Intent().setClass(this, SongsActivity.class);
spec = tabHost.newTabSpec("songs")
.setIndicator("Songs", res.getDrawable(R.drawable.ic_tab_artists))
.setContent(intent);
tabHost.addTab(spec);
tabHost.setCurrentTab(2); // 預設顯示第三個分頁
}
}
流程是這樣的:先用 getTabHost() 取得 TabHost 參照,接著為每個分頁用 newTabSpec(String) 建立 TabSpec,用 setIndicator(CharSequence, Drawable) 設定文字與圖示,再用 setContent(Intent) 指定要開啟的 Activity,最後 addTab() 加入。setCurrentTab(int) 決定預設顯示哪一頁。
5)在 AndroidManifest.xml 中為主 Activity 加上 NoTitleBar 主題,把預設標題列移除,騰出空間給分頁:
<activity android:name=".HelloWorld"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
執行看看結果——很可能會收到 java.lang.NullPointerException。這是相當典型的坑:TabHost 在 inflate 時找不到對應的內容,於是在初始化階段就掛掉。
解法其實很樸素:別忘了在 AndroidManifest.xml 中註冊那三個 Activity。少了註冊,Intent 啟動不到目標,TabSpec 的內容自然為 null。
<activity android:name=".AlbumsActivity" android:label="@string/app_name"></activity> <activity android:name=".ArtistsActivity" android:label="@string/app_name"></activity> <activity android:name=".SongsActivity" android:label="@string/app_name"></activity>
補上之後再執行,就能看到正常的分頁畫面:

圖 9、標籤佈局
七種佈局各有適用場景:介面元素單向排列用 LinearLayout 並搭配 weight 切分空間;需要靈活的相對關係用 RelativeLayout 減少巢狀;表格型資料用 TableLayout;資料清單用 ListView;圖片牆用 GridView;分頁切換用 TabHost。至於 AbsoluteLayout,了解即可,實務上盡量避開。
選對容器,往往比事後調 margin 更省事,也能讓效能與可維護性都更好。
MUI組件詳解(二):複選框、對話框、圖片輪播、圖標與輸入框
本文繼續梳理MUI的高頻組件,涵蓋複選框、對話框、圖片輪播、圖標和輸入框五個部分。 一、Checkbox(複選框) 複選框常用於多選場景,比如批量刪除、添加群聊等。默認c
仿 iOS 效果:ScrollView 滑動時自動隱藏底部懸浮按鈕
做 Android App 常要複刻 iOS 的互動細節。這次的需求是:頁面上的 ScrollView 滑動時,浮在底部的功能按鈕要以動畫收起;滑動停止後,再動畫回到原位
Fragment 生命週期完全解析
一、Fragment 是什麼 Fragment 自 Android 3.0(Honeycomb)起被引入,主要是為了回應平板等大屏設備上日益複雜的介面需求。當一個 Act
Android 文件下載入門:GET 請求的三個關鍵要點
從服務器拉取一個文本或文件到本地,是 Android 網絡編程最基礎的需求之一。實踐中真正容易出錯的地方並不多,但每一個都足以讓程序崩潰。 三個必須記住的要點 1. 不