Android 介面上常需要彈出對話框詢問或讓使用者選擇,這類元件統稱 Android Dialog,AlertDialog 的實作方式是建造者模式。這次要示範最基礎的普通選項(單選)對話框:點一下選項就立刻生效並關閉。
版面配置(layout):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="普通選項"
android:onClick="show2" />
</LinearLayout>
Java 功能實作:
public class AlertDialogDemo extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertdialog);
}
public void show2(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(this); // 實例化建造者
builder.setTitle("選花魁嘍"); // 設定標題
final String[] beautifulGirls = {"芙蓉姐姐", "鳳姐", "范爺", "我自己"};
// setItems:把陣列元素攤成各個 item,點選後即時處理並關閉
builder.setItems(beautifulGirls, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(AlertDialogDemo.this,
beautifulGirls[which] + "被選中啦",
Toast.LENGTH_SHORT).show();
}
});
builder.show(); // 顯示對話框
}
}
兩者外觀相似,行為卻不同。setItems 是「點到即完成」:監聽器回呼時對話框已準備關閉,which 直接就是使用者選的索引,不需要額外變數保存狀態。setSingleChoiceItems 則會顯示圓形選取鈕、需要搭配確定鍵,因此必須自己記住索引。
選擇時機的判斷很簡單:只需要一個「點下去就生效」的動作,用 setItems;需要「先挑再確認」或想預設某個選項,用 setSingleChoiceItems。若選項數量很多,則該改用 setMultiChoiceItems 或自訂 ListView/RecyclerView 版面,避免整齊度與捲動體驗失控。