編輯:關於 Android 程式設計
本章涵蓋:Toast 提示框、AlertDialog 對話框、特色對話框、自訂對話框。
目標:熟練掌握 Toast 與 Dialog 的用法,認識幾種常見的清單式對話框,並能自行設計自訂版面配置。
Toast 是一種浮於畫面最上層、用於顯示簡短訊息的視窗,最常用來回報各種動作的結果:
・正在編寫的郵件已自動存到草稿箱
・刪除某筆通訊記錄成功
它的特性很鮮明:只佔據一小塊畫面、目前的 Activity 依然存活且可與使用者互動、顯示一段時間後自動關閉,無需任何手動操作。

建立 Toast
第一步,用 Toast.makeText() 建立物件:
Context context = getApplicationContext(); CharSequence text = "Hello toast!"; int duration = Toast.LENGTH_SHORT; Toast toast = Toast.makeText(context, text, duration);
duration 決定顯示多久,有兩個取值:Toast.LENGTH_SHORT(約 2 秒)與 Toast.LENGTH_LONG(約 3.5 秒)。第二步,呼叫 show() 讓它真正出現——少了這一步,Toast 不會顯示,是最常見的初學者陷阱。
調整位置
預設位置是畫面底部水平居中。若要改,用 setGravity(),它接受三個參數:Gravity 常數(可用 | 組合)、x 偏移量、y 偏移量。
toast.setGravity(Gravity.TOP | Gravity.LEFT, 20, 30);
自訂外觀
先寫一個版面配置 toast_layout.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#FFF" />
</LinearLayout>
再以動態載入的方式套用到 Toast 上:
LayoutInflater li = getLayoutInflater();
View layout = li.inflate(R.layout.toast_layout_root, null);
TextView tv = (TextView) layout.findViewById(R.id.text);
tv.setText("custom toast");
Toast t = new Toast(getApplicationContext());
t.setGravity(Gravity.CENTER, 0, 0);
t.setDuration(Toast.LENGTH_SHORT);
t.setView(layout);
t.show();
Dialog 是一個讓使用者做決定或輸入資訊的視窗。它通常不佔滿畫面,與 Toast 不同——對話框不會自動關閉;對話框出現時,背後的 Activity 可見但無法互動。它本身不是 View,基類 Dialog 直接繼承自 Object。

系統已內建多種對話框類別:android.app.AlertDialog、DatePickerDialog、TimePickerDialog、ProgressDialog。其中 AlertDialog 是最常用的一個,它是 Dialog 的直接子類,可以包含標題、訊息文字、0 到 3 個按鈕,以及單選或多選清單。
AlertDialog 不能直接 new,必須透過 AlertDialog.Builder 建立。
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("信息提示");
builder.setMessage("这是一段提示內容");
AlertDialog alert = builder.create();
加上按鈕
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
簡單清單對話框
相當於把 ListView 放進對話框,用 setItems() 設定內容與事件:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("請選擇你最喜歡的運動");
builder.setItems(items, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
show.setText("你選中了《" + items[which] + "》");
}
});
builder.create().show();

單選清單對話框
用 setSingleChoiceItems(),第二個參數是預設勾選的索引:
builder.setSingleChoiceItems(items, 1, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
show.setText("你選中了《" + items[which] + "》");
}
});
builder.setTitle("請選擇要使用的情景模式");
builder.create().show();

複選清單對話框
用 setMultiChoiceItems(),第三個參數傳入初始勾選狀態陣列,回呼改用 OnMultiChoiceClickListener:
final boolean[] checkedItems = new boolean[] { false, true, false, true, false };
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("請選擇您喜愛的游戲");
builder.setMultiChoiceItems(items, checkedItems, new OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
checkedItems[which] = isChecked; // 記得同步狀態,否則重開時會跑掉
}
});
builder.create().show();

自訂清單對話框
若想完全掌控每一列的樣式,改用 setAdapter():
final String[] items = new String[] { "邁巴赫", "布加迪", "法拉利", "保時捷" };
AlertDialog.Builder builder = new AlertDialog.Builder(this)
.setTitle("自定義列表項對話框")
.setIcon(R.drawable.tools)
.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, items),
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
show.setText("你選中了《" + items[which] + "》");
}
});
builder.create().show();

除了清單,系統還提供了幾個針對特定情境設計的對話框:DatePickerDialog 讓使用者挑日期、TimePickerDialog 挑時間、ProgressDialog 顯示等待進度。它們的共同點是「輸入格式固定」,因此直接用現成元件,比自訂版面配置更不容易出錯,也更貼近系統的操作習慣。
所謂自訂,就是要擺脫對話框的固有樣式。思路只有兩步:先在 res/layout 下把想要的版面配置寫成 XML,再用 Dialog 提供的能力把它裝進去。
這裡有個常見的坑:直接使用 Dialog 時,若不設定 Title,標題位置仍會保留一片空白,看起來很突兀。改用 AlertDialog 就能避開這個問題。
LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.custom_dlg, null); AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); builder.setView(layout); AlertDialog alertDialog = builder.create(); alertDialog.show();

把 Activity 變成對話框
還有一種更靈活的思路:對話框本質上就是一個視窗,因此你可以把某個 Activity 的主題設成對話框風格,讓它「看起來像彈窗,實際上是獨立頁面」。做法是在 AndroidManifest.xml 中為該 Activity 指定 android:theme,例如 Theme.Dialog 或 Theme.Translucent,並記得加上 intent-filter 讓它能被啟動。
<intent-filter>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

這種做法的好處是:Activity 有自己的生命週期,旋轉螢幕、返回鍵堆疊都由系統處理,比在一個大 Activity 裡管理多個 Dialog 物件要清爽得多。
最後提醒一個實務細節:無論用哪一種對話框,都要避免在 Activity 已銷毀後再彈視窗,否則會出現 android.view.WindowLeaked 的錯誤。把 Dialog 的建立與釋放綁定到 Activity 生命週期,是最省事的防禦方式。
ADB 指令入門到實戰:環境配置、裝置連線與日常開發技巧
adb(Android Debug Bridge)這個名字大概每個做 Android 的人都聽過,但真正把它用順手的人並不多。這段時間參與 Android 系統層面的開發
結合原始碼深入剖析 ViewGroup 中的事件分發流程
序言 這篇博文並不是對事件分發機制的全面介紹,只是從原始碼的角度,分析 ACTION_DOWN、ACTION_MOVE、ACTION_UP 事件在 ViewGroup 中
Android 自定義輪播圖控件:ViewPager 自動滾動加圓點指示器
說到製作輪播圖,多數人第一反應就是用 ViewPager。它自帶滑動能力,我們只要讓它定時自動翻頁,再補上一排小圓點作為位置指示,一個典型的 Banner 輪播就成型了。
Android 自定義滾動選擇器(Picker)完整實例代碼
本文分享一個自定義滾動選擇器的完整實現,先看看效果:它的核心思路是:用一個自定義 View,把數據列表循環排列,通過手指滑動改變偏移量,再用拋物線函數計算每個選項的字號與