編輯:關於 Android 程式設計
在 Android 中,Dialog 是與對話框相關的類,主要承擔各類提示與交互的作用。它大致可以分為以下幾種:
AlertDialog:警告(提示)對話框;ProgressDialog:進度對話框;DatePickerDialog:日期選擇對話框;TimePickerDialog:時間選擇對話框;以及自定義對話框。下面逐一展開介紹。
AlertDialog 繼承自 Dialog,對一些常用對話框進行了封裝。值得注意的是,它存在兩個實現,分別位於不同的包中:
Android 原生包 android.app.AlertDialog:並未針對不同系統版本做適配,在各個手機系統上顯示的樣式各不相同(不推薦)。
v7 支持包 android.support.v7.app.AlertDialog:遵循 Google 推出的 Material Design 設計,並對低版本系統做了適配,支持到 Android 2.1(API 7)以上(推薦)。
下文統一使用 v7 版本的 AlertDialog。它的使用步驟如下:
① 創建 AlertDialog.Builder 對象;② 調用 Builder 的方法設置圖標、標題、內容、按鈕等,常用方法有 setTitle()(標題)、setIcon()(圖標)、setMessage()(信息)、setPositiveButton()(確定按鈕)、setNegativeButton()(取消按鈕)、setNeutralButton()(中立按鈕);③ 調用 create() 生成 AlertDialog;④ 調用 show() 顯示,調用 dismiss() 銷毀。
public void dialog1(View view){
// 1. 創建 Builder 對象,注意此處必須傳入 Activity
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. 設置常用屬性
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle("提示");
builder.setMessage("這是一個基礎的 AlertDialog");
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AlertDialogActivity.this, "確定", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
builder.setNeutralButton("中間", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
// 3. 創建 AlertDialog
AlertDialog dialog = builder.create();
// 4. 顯示
dialog.show();
}

這裡有幾點需要注意:AlertDialog 的 Builder 雖然構造時傳入的是 Context,但實際上必須是 Activity 對象;dimiss() 為銷毀方法;setPositiveButton、setNegativeButton、setNeutralButton 三個方法對應不同位置與含義的按鈕。此外,還可以用鏈式調用一口氣完成創建:
AlertDialog dialog = new AlertDialog.Builder(this)
.setIcon(R.mipmap.ic_launcher)
.setTitle("提示")
.setMessage("這是一個基礎的 AlertDialog")
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
})
.setNeutralButton("中間", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
}).create();
由於 AlertDialog 繼承自 Dialog,它天然具備 Dialog 的特性(這些特性對所有對話框都適用)。常用的兩個方法是:
setCancelable(boolean flag):控制點擊返回鍵時 Dialog 是否消失,true 表示消失,false 表示無效果。setCanceledOnTouchOutside(boolean cancel):控制點擊對話框以外區域時是否消失。
// 點擊返回鍵不取消對話框 dialog.setCancelable(false); // 觸摸對話框以外區域不消失 dialog.setCanceledOnTouchOutside(false);
注意:這兩個方法是
Dialog的方法,而非Builder的方法。
實現單選有兩種方式,分別對應 setItems 和 setSingleChoiceItems。setItems 點擊條目後立即消失並觸發回調;setSingleChoiceItems 則是帶圓圈的普通單選效果,需點擊確定後才隱藏。

setItems() 實現:
final String[] sex = {"男","女"};
AlertDialog dialog = new AlertDialog.Builder(this)
.setItems(sex, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// which 表示點擊的索引
Toast.makeText(AlertDialogActivity.this, sex[which], Toast.LENGTH_SHORT).show();
}
}).create();
dialog.show();
setSingleChoiceItems() 實現:
public void choice_single(View view){
final String[] sex = {"男","女"};
AlertDialog dialog = new AlertDialog.Builder(this)
.setSingleChoiceItems(sex, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AlertDialogActivity.this, sex[which], Toast.LENGTH_SHORT).show();
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
})
.create();
dialog.show();
}
兩者的比較:setItems 只能選擇一次,選完即消失,無法修改;setSingleChoiceItems 可設置默認選中項,支持多次選擇,直到點擊確定等操作才關閉。二者選中事件的回調邏輯相同。
使用 setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, OnMultiChoiceClickListener listener) 可實現多選。三個參數分別是:可選條目數組、與條目一一對應的默認勾選狀態(false 未選、true 默認選中)、以及選項變化時的回調。

final String[] like = {"足球","籃球","乒乓球","排球"};
final boolean[] check = {false,false,true,true};
AlertDialog dialog = new AlertDialog.Builder(this)
.setMultiChoiceItems(like, check, new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// which 為數據變化的索引,isChecked 為變化結果
check[which] = isChecked;
}
})
.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// 根據 check 中的值處理勾選結果
}
})
.create();
核心在於 OnMultiChoiceClickListener:數據變化時會回調此方法,我們需要在其中同步保存修改後的狀態。
ProgressDialog 同樣繼承自 Dialog,擴展了緩衝加載提示的功能,分為圓形轉圈加載與水平進度條兩種樣式。

public void progress_circle(View view){
final ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 圓形旋轉樣式
pd.setCancelable(false); // 返回鍵不取消
pd.setCanceledOnTouchOutside(false); // 觸摸外部不消失
pd.setIcon(R.mipmap.ic_launcher);
pd.setTitle("提示");
pd.setOnDismissListener(new DialogInterface.OnDismissListener() {
@Override
public void onDismiss(DialogInterface dialog) { }
});
pd.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) { }
});
pd.setMessage("這是一個圓形進度條");
pd.show();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
pd.dismiss();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
這裡直接 new 出 ProgressDialog,無需 Builder。通過把 setProgressStyle 設為 STYLE_SPINNER 呈現圓形加載效果。dismiss() 與 cancel() 都能隱藏對話框,但含義不同:cancel() 只是隱藏、並不銷毀,會回調 setOnCancelListener;dismiss() 則銷毀對話框,回調 setOnDismissListener。
推薦使用
dismiss()。因為若只調用了cancel,Activity 結束時仍需手動調用dismiss,否則未銷毀的 dialog 會導致內存洩露。
public void progress_horizontal(View view){
final ProgressDialog pd = new ProgressDialog(this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 水平進度條
pd.setCancelable(false);
pd.setCanceledOnTouchOutside(false);
pd.setIcon(R.mipmap.ic_launcher);
pd.setTitle("提示");
pd.setMax(100); // 默認為 100
pd.setMessage("這是一個水平進度條");
pd.show();
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (i < 100) {
try {
Thread.sleep(200);
pd.incrementProgressBy(1); // 每次進度 +1
i++;
} catch (Exception e) { }
}
pd.dismiss();
}
}).start();
}
把樣式設為 STYLE_HORIZONTAL,用 setMax() 設置總進度,用 incrementProgressBy(1) 動態遞增,最後銷毀 dialog。
這是 Android 提供的原生控件,使用簡單,但因為沒有對不同系統做適配,各版本顯示可能不同,一般只作了解,實際項目中多采用自定義方案。

public void dialog_date(View view){
// 獲取系統當前時間
Calendar instance = Calendar.getInstance();
int year = instance.get(Calendar.YEAR);
int month = instance.get(Calendar.MONTH); // 月份從 0 開始
int day = instance.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
// 回調的 month 需 +1 才是真實月份
Toast.makeText(AlertDialogActivity.this, year+"-"+(monthOfYear+1)+"-"+dayOfMonth, Toast.LENGTH_SHORT).show();
}
}, year, month, day);
dialog.show();
}
通過 Calendar 拿到當前時間,再傳入 DatePickerDialog 的構造方法。其構造方法共 5 個參數:當前 Activity、數據回調 OnDateSetListener、年、月、日。特別注意:Java 時間中年、天、時、分從直觀值取即可,唯獨月份從 0 開始,傳值和回調時都需要 +1 或 -1 修正。此外,彈窗中粉色區域的顏色取自應用主題裡的 colorAccent:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item> <!-- 設置 dialog 的顏色 -->
</style>
用法與 DatePickerDialog 基本一致。

public void dialog_time(View view){
Calendar instance = Calendar.getInstance();
int hour = instance.get(Calendar.HOUR_OF_DAY);
int minute = instance.get(Calendar.MINUTE);
TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Toast.makeText(AlertDialogActivity.this, hourOfDay+"-"+minute, Toast.LENGTH_SHORT).show();
}
}, hour, minute, true);
dialog.show();
}
構造方法的 5 個參數分別是:當前 Activity、數據回調 OnTimeSetListener、小時、分鐘,以及是否使用 24 小時制(false 為 12 小時制,true 為 24 小時制)。
由於系統自帶的 dialog 難以很好地適配不同版本的樣式,實際項目中常常需要自定義。實現步驟為:① 編寫自定義布局;② 自定義類繼承 Dialog 並重寫構造方法;③ 設置 dialog 主題;④ 用 setContentView 加載布局;⑤ 查找控件並編寫邏輯。

自定義布局 dialog_simple.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="250dp"
android:layout_height="400dp"
android:background="@drawable/shape_dialog_psd_bg"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="一個簡單的自定義 dialog" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:layout_margin="10dp">
<TextView
android:id="@+id/dialog_simple_cancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="關閉"
android:textSize="16sp" />
</LinearLayout>
</LinearLayout>
很多需求會模仿 iOS,把外框做成圓角矩形。Dialog 並沒有提供相應方法,需要從布局的背景入手,用 shape 資源實現圓角:
<shape xmlns:android="https://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#fff" />
<stroke android:color="#ececec" android:width="1dp" />
</shape>
接著編寫 CustomDialog 類:
public class SimpleDialog extends Dialog implements View.OnClickListener {
public SimpleDialog(Context context) {
// 設置自定義樣式
super(context, R.style.CustomDialog);
// 加載自定義布局
setContentView(R.layout.dialog_simple);
initView();
}
private void initView() {
findViewById(R.id.dialog_simple_cancel).setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.dialog_simple_cancel:
this.dismiss();
break;
}
}
}
關鍵步驟:重寫單參數構造方法,在其中調用父類構造方法傳入 dialog 樣式,再用 setContentView() 設置布局,最後查找控件並編寫邏輯。這裡特別要強調設置樣式的重要性——若不設置,在低於 Android 5.0 的系統上樣式會錯亂。常用的樣式定義如下:
<style name="CustomDialog" parent="@android:style/Theme.Dialog">
<item name="android:windowIsFloating">true</item> <!-- 浮現在 Activity 之上 -->
<item name="android:windowNoTitle">true</item> <!-- 無標題 -->
<item name="android:windowBackground">@android:color/transparent</item> <!-- 背景透明 -->
</style>
自定義 Dialog 大致就這麼多,複雜無非體現在界面與邏輯上。

定義動畫需要通過 XML 文件編寫。進入動畫 dialog_anim_enter.xml 與離開動畫 dialog_anim_exit.xml 分別定義進出效果(這裡以 duration 為例):
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="500">
</set>
需要注意的是,動畫以 dialog 自身的左上角為原點進行偏移,效果相對於本身。
編寫動畫樣式:
<style name="DialogAnim" parent="@android:style/Animation">
<item name="android:windowEnterAnimation">@anim/dialog_anim_enter</item>
<item name="android:windowExitAnimation">@anim/dialog_anim_exit</item>
</style>
通過 dialog.getWindow().setWindowAnimations(int resId) 應用動畫:
public void dialog_anim(View view){
SimpleDialog dialog = new SimpleDialog(this);
dialog.getWindow().setWindowAnimations(R.style.DialogAnim);
dialog.show();
}
這種動畫設置方法對所有 dialog 都適用,包括系統自帶的 AlertDialog。
有兩種實現方式。第一種直接調用 dialog.getWindow().setLayout(100, 100);;第二種通過 getAttributes() 獲取並修改參數:
public void dialog_size(View view) {
SimpleDialog dialog = new SimpleDialog(this);
// 方式一:dialog.getWindow().setLayout(100, 100);
// 方式二:
WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
params.height = 100;
params.width = 100;
dialog.getWindow().setAttributes(params);
dialog.show();
}
其實方式一的內部實現正是方式二。方式二拿到的 params 裡還包含許多其他顯示屬性,不僅僅是寬高。這兩種方法同樣對所有 dialog 通用。
Android 中的訊息通知:NotificationManager 與 Notification 用法整理
來談談 Notification。它最常見的場景是電話、簡訊、郵件、鬧鐘——手機狀態條上會浮現一個小圖示提示使用者處理,從上方滑下狀態條就能展開並處理這則快訊。Andro
Android 資料庫通用化:用註解與反射建立映射
本文延續 Android 資料庫通用化主題,重點在於利用註解與反射,讓實體類與資料表自動對應。 表名取得 可定義 TableName 註解,標記在實體類上,並於執行期透
Android 仿微信朋友圈九宮格多圖展示控件
一、簡介 這是一個用來實作類似微信朋友圈、微博那種九宮格圖片展示的控件,透過自訂 ViewGroup 完成,使用方式單純。 多張圖片時會依螢幕寬度自動適配;只有單張圖片時
Adapter 模式實戰:重構 Android 圓形菜單
在 Android 開發中,炫目的自訂 UI 往往最能吸引目光,但真正能做出穩定且可擴充的效果,取決於開發者是否理解自訂 View 的測量、布局與事件流程。本文以一個圓形