編輯:關於 Android 程式設計
Dialog 是 Android 里最常被使用、也最容易被寫得雜亂的元件。本文把八種常見型態一次整理出來,包含普通提示、列表、單選、多選、等待、進度、輸入與自訂版面,最後再說明如何在顯示前後插入自己的邏輯。
最基礎的形式,透過 AlertDialog.Builder 串起圖示、標題、訊息與按鈕。setXxx 方法都會回傳 Builder 本身,因此可以鏈式呼叫。
兩個按鈕:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonNormal = (Button) findViewById(R.id.button_normal);
buttonNormal.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showNormalDialog();
}
});
}
private void showNormalDialog() {
/* @setIcon 設置圖標
* @setTitle 設置標題
* @setMessage 設置提示訊息 */
final AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
normalDialog.setIcon(R.drawable.icon_dialog);
normalDialog.setTitle("我是一個普通Dialog");
normalDialog.setMessage("你要點擊哪一個按鈕呢?");
normalDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// To-do
}
});
normalDialog.setNegativeButton("關閉", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// To-do
}
});
normalDialog.show();
}
}
三個按鈕時,中間那颗用 setNeutralButton:
private void showMultiBtnDialog() {
AlertDialog.Builder normalDialog = new AlertDialog.Builder(MainActivity.this);
normalDialog.setIcon(R.drawable.icon_dialog);
normalDialog.setTitle("我是一個普通Dialog")
.setMessage("你要點擊哪一個按鈕呢?");
normalDialog.setPositiveButton("按鈕1", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
normalDialog.setNeutralButton("按鈕2", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
normalDialog.setNegativeButton("按鈕3", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
normalDialog.show();
}
setItems 接受字串陣列,回呼中的 which 就是被點擊的索引(從 0 起算):
private void showListDialog() {
final String[] items = { "我是1", "我是2", "我是3", "我是4" };
AlertDialog.Builder listDialog = new AlertDialog.Builder(MainActivity.this);
listDialog.setTitle("我是一個列表Dialog");
listDialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "你點擊了" + items[which],
Toast.LENGTH_SHORT).show();
}
});
listDialog.show();
}
第二個參數是預設選項索引。實作上用一個變數記住選擇,待使用者按確定後才取用,避免選了卻被取消的情況被誤判:
int yourChoice;
private void showSingleChoiceDialog() {
final String[] items = { "我是1", "我是2", "我是3", "我是4" };
yourChoice = -1;
AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(MainActivity.this);
singleChoiceDialog.setTitle("我是一個單選Dialog");
singleChoiceDialog.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
yourChoice = which;
}
});
singleChoiceDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (yourChoice != -1) {
Toast.makeText(MainActivity.this, "你選擇了" + items[yourChoice],
Toast.LENGTH_SHORT).show();
}
}
});
singleChoiceDialog.show();
}
第二個參數是初始勾選狀態陣列,第三個回呼帶有 isChecked 指出這次是勾選還是取消:
ArrayList<Integer> yourChoices = new ArrayList<>();
private void showMultiChoiceDialog() {
final String[] items = { "我是1", "我是2", "我是3", "我是4" };
final boolean initChoiceSets[] = { false, false, false, false };
yourChoices.clear();
AlertDialog.Builder multiChoiceDialog = new AlertDialog.Builder(MainActivity.this);
multiChoiceDialog.setTitle("我是一個多選Dialog");
multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
new DialogInterface.OnMultiChoiceClickListener() {
@Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
if (isChecked) {
yourChoices.add(which);
} else {
yourChoices.remove(Integer.valueOf(which));
}
}
});
multiChoiceDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String str = "";
for (int i = 0; i < yourChoices.size(); i++) {
str += items[yourChoices.get(i)] + " ";
}
Toast.makeText(MainActivity.this, "你選中了" + str, Toast.LENGTH_SHORT).show();
}
});
multiChoiceDialog.show();
}
這裡有個經典陷阱:yourChoices.remove(which) 傳入的是 int,會被當成索引而非物件,導致刪錯元素,因此必須包成 Integer.valueOf(which) 才會走物件比對。
具備遮罩能力,可阻擋其他控件互動。設為不可取消後,必須由程式在下載或請求結束時主動關閉:
private void showWaitingDialog() {
ProgressDialog waitingDialog = new ProgressDialog(MainActivity.this);
waitingDialog.setTitle("我是一個等待Dialog");
waitingDialog.setMessage("等待中...");
waitingDialog.setIndeterminate(true);
waitingDialog.setCancelable(false);
waitingDialog.show();
}
private void showProgressDialog() {
final int MAX_PROGRESS = 100;
final ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setProgress(0);
progressDialog.setTitle("我是一個進度條Dialog");
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(MAX_PROGRESS);
progressDialog.show();
// 模擬進度遞增,每 100ms 加 1
new Thread(new Runnable() {
@Override
public void run() {
int progress = 0;
while (progress < MAX_PROGRESS) {
try {
Thread.sleep(100);
progress++;
progressDialog.setProgress(progress);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
progressDialog.cancel();
}
}).start();
}
用 setView 塞進一個 EditText 即可:
private void showInputDialog() {
final EditText editText = new EditText(MainActivity.this);
AlertDialog.Builder inputDialog = new AlertDialog.Builder(MainActivity.this);
inputDialog.setTitle("我是一個輸入Dialog").setView(editText);
inputDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, editText.getText().toString(),
Toast.LENGTH_SHORT).show();
}
}).show();
}
版面檔 dialog_customize.xml:
<!-- res/layout/dialog_customize.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
用 LayoutInflater 把版面撐開後交給 setView,就能放進任何自訂內容:
private void showCustomizeDialog() {
AlertDialog.Builder customizeDialog = new AlertDialog.Builder(MainActivity.this);
final View dialogView = LayoutInflater.from(MainActivity.this)
.inflate(R.layout.dialog_customize, null);
customizeDialog.setTitle("我是一個自定義Dialog");
customizeDialog.setView(dialogView);
customizeDialog.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText edit_text = (EditText) dialogView.findViewById(R.id.edit_text);
Toast.makeText(MainActivity.this, edit_text.getText().toString(),
Toast.LENGTH_SHORT).show();
}
});
customizeDialog.show();
}
若希望在-dialog建立或顯示時做一些事(例如初始化列表、設定預設選項),可以改寫 Builder 的 create() 與 show()。前者只在第一次建立時呼叫,後者每次顯示都會觸發,這個差異在 Dialog 被重複使用時很重要。
private void showListDialog() {
final String[] items = { "我是1", "我是2", "我是3", "我是4" };
AlertDialog.Builder listDialog = new AlertDialog.Builder(MainActivity.this) {
@Override
public AlertDialog create() {
items[0] = "我是No.1";
return super.create();
}
@Override
public AlertDialog show() {
items[1] = "我是No.2";
return super.show();
}
};
listDialog.setTitle("我是一個列表Dialog");
listDialog.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) { }
});
/* @setOnDismissListener Dialog 銷毀時調用
* @setOnCancelListener Dialog 被取消時調用 */
listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
Toast.makeText(getApplicationContext(), "Dialog被銷毀了",
Toast.LENGTH_SHORT).show();
}
});
listDialog.show();
}
最後兩點實務建議:ProgressDialog 已被官方標記為 deprecated,因為它在背景執行時無法更新、旋轉螢幕後容易洩漏,改用 Toolbar 加上非阻斷式的進度指示器體驗更好;另外所有 Dialog 都應持有 Activity 而非 Application 的 Context,並在 onStop 時呼叫 dismiss,否則螢幕旋轉後會出現「WindowLeaked」的錯誤日誌。
Android 原型模式詳解:淺拷貝與深拷貝的實戰比較
原型模式屬於創建型設計模式,主要用於建立昂貴或耗時的物件。它透過複製既有物件來產生新物件,藉此節省時間與記憶體。 模式結構 Client:客戶端,呼叫複製方法的類別
Android WindowManager解析與原理實踐(附Window機制完整梳理)
近來在網上看到有人提交了一個有趣的案例:應用可以開啟一個後台Service,偵測當前頂部應用,若為QQ或相關應用,就彈出一個自定義Window來誘騙使用者輸入帳號密碼。這
研究稱 Android 4.4 比 iOS 7.1 更穩定
根據 Crittercism 發布的《移動體驗基準測試報告》,研究人員在 2582 款設備上測試了 106 種操作系統與 691 個網路運營商。結果顯示,Android
Android Support Design 完全解析(七):CoordinatorLayout 與 Behavior
概述 前面我們簡單接觸過 CoordinatorLayout,本篇將深入剖析這個 ASD(Android Support Design)庫中最重要、也最強大的控件。回想一