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

Stack Overflow 排錯翻譯:在 Android 中關閉 AlertDialog

編輯:關於 Android 開發

Stack Overflow 排錯翻譯:在 Android 中關閉 AlertDialog

轉自:https://www.lanqibing.com/archives/783.html

原始提問

在下面的代碼中,我嘗試關閉(dismiss)AlertDialog,但始終沒有生效。奇怪的是,只要把 compareKeys() 這個函數去掉,dismiss 就能正常工作。請問要如何才能在調用 compareKeys() 之後依然正常關閉對話框?

public void promptAdministratorPassword() {
    AlertDialog.Builder alert = new AlertDialog.Builder(this);

    alert.setTitle("Alert!");
    alert.setMessage("Please enter your password: ");

    // 用 EditText 接收用戶輸入
    final EditText input = new EditText(this);
    alert.setView(input);

    alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            password = input.getText().toString();

            if (password.equals("password")) {
                try {
                    compareKeys();
                } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e) {
                    e.printStackTrace();
                }
            }
            dialog.dismiss();
        }
    });

    alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int whichButton) {
            // 已取消
        }
    });

    alert.show();
}

接受的答案

把 dialog.dismiss() 提到 password = input.getText().toString() 之前調用,並且也在 setNegativeButton 的 OnClickListener 裡補上一句 dialog.dismiss()。

為什麼會這樣

這是一個相當典型的誤解。點擊 AlertDialog 的按鈕時,對話框並不會自動關閉——是否關閉完全由你在監聽器裡決定。原代碼之所以「去掉 compareKeys() 就正常」,很可能只是巧合:compareKeys() 執行時間較長或拋出受檢異常,掩蓋了真實症狀,讓人誤以為是它阻礙了關閉。

更穩健的寫法是先關閉再處理業務邏輯,或者直接使用帶有自動 dismiss 行為的構造方式。若需要在異步任務完成後再關閉,也應保存 dialog 引用並在合適的時機調用,同時注意判空與 Activity 是否仍然存活,避免內存洩漏與 BadTokenException。

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