首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android AlertDialog 重複點擊導致崩潰:單例模式複用 Dialog 解決

     編輯:程式設計疑難解答

問題現象

每次點擊「選擇」按鈕都 `new AlertDialog.Builder(...).create()`,快速多次點擊導致多個 Dialog 疊加,系統拋出 `WindowManager$BadTokenException` 或 ANR。

解決方案:成員變量持有 Dialog 實例

public class MainActivity extends Activity implements View.OnClickListener {
    private AlertDialog mLoginDialog; // 成員變量
    private View mLoginView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        LayoutInflater inflater = LayoutInflater.from(this);
        mLoginView = inflater.inflate(R.layout.login, null);
        findViewById(R.id.bt1).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.bt1) {
            if (mLoginDialog == null) {
                mLoginDialog = new AlertDialog.Builder(this)
                    .setTitle("用戶登錄")
                    .setView(mLoginView)
                    .setPositiveButton("確定", null)
                    .setNegativeButton("取消", null)
                    .create();
            }
            mLoginDialog.show();
        }
    }
}

關鍵點

  • `mLoginDialog` 只創建一次,後續直接 `show()`。
  • 若需每次顯示重置輸入框,在 `show()` 前手動清空 `mLoginView` 中的 `EditText`。
  • Activity 銷毀時 Dialog 會自動釋放,無需手動 dismiss。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved