簡體   English   中英

警報對話框未顯示

[英]Alert dialog is not displaying

大家好,我正在通過單擊一個按鈕在 android 中創建一個警報對話框。 我使用了 XML 的 onClick 屬性和調用函數。 我的代碼是

public void selectPhoneType(View view)
{
    String [] item = {"Home", "Work", "Mobile", "Work Fax", "Home Fax", "Pager", "Other", "Custom"};
    AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
    builder.setTitle("Select Label");
    AlertDialog alert = builder.create();
    alert.show();}

但是此代碼沒有顯示警報並給出錯誤,例如

BadTokenException: Unable to add window -- token null is not for an application. 

請告訴我這段代碼有什么問題。

new AlertDialog.Builder(getApplicationContext());

我認為這是問題所在。 你有沒有嘗試過:

new AlertDialog.Builder(YourActivityClassName.this);

傳遞requireActivity()而不是requireContext()對我有用..!! 我認為它需要活動上下文!

如果您在后台線程中調用對話框代碼,那么它將不起作用。 您應該在主線程中調用與 UI 相關的代碼,如果您不這樣做,那么它不會向您顯示對話框。

  1. 如果要在后台任務中顯示對話框,請改用處理程序。

    新的 Handler().post(新的 Runnable(){ showDialog(); })

  2. 確保調用了create()show()方法。

  3. 永遠不要忘記第 1 點和第 2 點。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM