Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AlertDialog 對話框實作:用 Builder 串起標題、訊息與雙向按鈕

編輯:關於 Android 程式設計

當流程走到需要使用者明確確認的關頭——刪除資料、離開頁面、跳轉外部網站——對話框是最合適的元件。Android 的 AlertDialog.Builder 用串接的方式把這件事寫得相當乾淨。

版面:先放一顆觸發按鈕

版面檔很單純,一個置中偏上的 Button 就夠:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/button"
        android:id="@+id/button" />

</RelativeLayout>

文字記得抽到 strings.xml,別寫死。這裡我放了 app_name、hello_world、menu_settings 與 button 四筆。

Java:Builder 的串接寫法

Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        AlertDialog.Builder builder =
                new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("hopean.com")
                .setMessage("你確定要訪問我們網站嗎?")
                .setCancelable(false)
                .setPositiveButton("確定", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Intent intent = new Intent(
                                Intent.ACTION_VIEW,
                                Uri.parse("https://www.hopean.com"));
                        startActivity(intent);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }
});

幾個值得留意的環節

setCancelable(false) 讓使用者無法靠返回鍵或點擊外部關閉對話框。這適合「必須做出選擇才能繼續」的情境。若為預設的 true,返回鍵就會直接把框收掉,等於跳過了確認。

setPositiveButton 與 setNegativeButton 分別對應右側與左側按鈕。除了這兩個,還有 setNeutralButton 可做第三個選項,例如「稍後再說」。

「確定」裡用 Intent.ACTION_VIEW 加上網址,是把開啟瀏覽器的動作交給系統處理,不必自己指定要哪個瀏覽器。「取消」則呼叫 dialog.cancel() 關閉。

builder.create() 建立物件,alert.show() 才真正顯示。這兩步常被寫成一串行,但分開寫的好處是——你有一個 alert 變數可以在後續做進階控制,例如動態替換按鈕文字或調整視窗位置。

一個小提醒

對話框不宜過度使用。每一次跳出確認框,都在消耗使用者對你的信任。真正破壞性、不可逆的操作才值得用它;其餘場合考慮 Snackbar 搭配「復原」按鈕,體驗通常更好。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved