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

Android AlertDialog:如何取得 PositiveButton 的控制權

編輯:關於 Android 程式設計

AlertDialog 建立後,其內部的 Button 是被 AlertController 持有的,外部拿不到參照,因此無法直接改樣式或控制顯示。本文記錄兩種繞過這個限制的做法。

做法一:在 onClick 中取得 Button 物件

final AlertDialog.Builder alert = new AlertDialog.Builder(CloudSyncActivity.this);
alert.setIcon(getResources().getDrawable(R.drawable.about));
alert.setTitle("標題");
alert.setMessage("輸入提示資訊");

alert.setPositiveButton("確認", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // 取得按鈕物件
        Button positiveButton = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE);
        // 對按鈕進行操作
        positiveButton.setVisibility(View.GONE);
    }
});

alert.setNegativeButton("取消", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        // 取消時的處理
    }
});

alert.show();

關鍵是 ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_POSITIVE)。這個方法(API 8 以後提供)能拿到 dialog 內部的按鈕 view,之後就能任意設定 visibility、enabled、文字或背景。

不過要注意:在 onClick() 裡取得按鈕時,dialog 正在關閉流程中,改樣式的視覺效果通常不明顯。更實用的做法是在 show() 之後才取得:

AlertDialog dialog = alert.create();
dialog.show();

Button positiveButton = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
positiveButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        // 自訂點擊行為:例如先驗證輸入,不通過就不關閉
        if (!isValid()) {
            Toast.makeText(context, "請先填寫完整", Toast.LENGTH_SHORT).show();
            return;   // 不呼叫 dismiss,dialog 保持開啟
        }
        doSubmit();
        dialog.dismiss();
    }
});

這技巧常用於「輸入驗證不通過時不讓對話框關掉」的需求,因為覆寫 PositiveButton 的 OnClickListener 後,它就不再走預設的關閉流程了。

做法二:用反射改 mShowing(不推薦)

原始範例試著透過反射操作 mShowing 欄位來控制關閉:

try {
    Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
    field.setAccessible(true);
    field.set(dialog, false);   // 設為已關閉
    dialog.dismiss();
} catch (Exception e) {
    e.printStackTrace();
}

這段程式碼有幾個問題值得指出:

· 依賴內部實作。mShowing 是 Dialog 的 private 欄位,Android 版本升級後欄位名或結構都可能改變,屆時反射會靜默失敗(被 catch 吞掉),造成難以追蹤的 bug。

· 邏輯自相矛盾。範例中 PositiveButton 分支設為 false,NegativeButton 分支卻設為 true,但註解都寫「表示對話框已關閉」,顯然是複製貼上時改漏了。

· 在 onClick 裡操作為時已晚。點擊發生後 dialog 的關閉流程已經啟動,此時改 mShowing 沒有實際意義。

· 例外被完全吞掉。catch (Exception e) {} 這種空處理會讓問題隱形。

結論:用做法一的 getButton() 就够了,它是官方 API、穩定可靠,不必動用反射。

其他常見的按鈕控制需求

讓 PositiveButton 預設 disabled:

dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);

點擊後不自動關閉:在 show() 之後用 setOnClickListener 覆寫,並自行決定何時 dismiss()(如上所示)。

整體換樣式:若只是要改外觀,用 ContextThemeWrapper 搭配自訂 style 會比逐顆按鈕操作乾淨:

AlertDialog dialog = new AlertDialog.Builder(
        new ContextThemeWrapper(this, R.style.MyAlertDialogStyle)).create();
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved