2011-12-02 50 views
2

我打開一個AlertDialog呈現用戶的文本輸入,以命名一個新項目AlertDialog.Builder崩潰。這在第一次打開時工作正常。但第二次點擊啓動對話框的按鈕時,應用程序崩潰。我得到這個錯誤:Android的 - 啓動它,當第二次

12-02 16:01:04.205: E/AndroidRuntime(515): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. 

我不知道這意味着什麼或者我稱之爲removeView()

這裏是我的代碼:

public class ShoppingList extends Activity implements OnClickListener{ 

     private AlertDialog.Builder m_alert; 
     private Context m_context; 

     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.shopping_list); 
      m_context = getApplicationContext(); 
      LayoutInflater inflater = (LayoutInflater) m_context.getSystemService(LAYOUT_INFLATER_SERVICE); 
      View layout = inflater.inflate(R.layout.add_shopping_list, (ViewGroup) findViewById(R.id.layout_root)); 
      m_alert = new AlertDialog.Builder(ShoppingList.this); 
      //final EditText input = new EditText(this); 
      //m_alert.setView(input); 
      m_alert.setView(layout); 
      final EditText input = (EditText)layout.findViewById(R.id.new_sl_name); 
      m_alert.setPositiveButton(R.string.add_button, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        String value = input.getText().toString().trim(); 
        Toast.makeText(m_context, value, 
          Toast.LENGTH_SHORT).show(); 
        m_alert.create(); 
       } 
      }); 

      m_alert.setNegativeButton(R.string.cancel_button, 
       new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int whichButton) { 
         dialog.cancel(); 
         m_alert.create(); 
        } 
       } 
      ); 

      // Add Button. . . 
      Button addButton = (Button)findViewById(R.id.add_sl_button); 
      addButton.setOnClickListener(this); 
     } 

     public void onClick(View v) { 
      if(!this.isFinishing()) 
       m_alert.show(); 
     } 
    } 
+0

你可以發佈完整的堆棧跟蹤嗎?它應該指出失敗的行號。 –

回答

1

m_alert.create()被點擊的正和負的按鈕之後被調用。這是做什麼的,是再次創建對話框。

使用m_alert.dismiss()來代替,所以你的對話框關閉,您可以再次使用它以後

+0

謝謝!這是問題。我的印象是我可以重複使用對話框。 – jasonlg3d

2

這是最有可能的,因爲你是在一個錯誤的地方使用m_alert.create();

檢查本教程的對話框:Dialogs

0

這可能有助於某人。我在筆記本電腦上構建了大部分應用程序。我剛把我的辦公室放回來,讓我的電腦開機。當我嘗試從我的PC上的雲存儲中加載我的項目時,似乎發生了一些構建錯誤。對於AlertDialog.Builder崩潰我注意到,我的電腦在新鮮的Android Studio安裝設置我的「導入」到android.support.v7.app.AlertDialog,而不是android.app.AlertDialog出於某種原因。我刪除了導入並重新選擇了android.app.AlertDialog,一切正常。我不知道這是一個錯誤還是Android Studio如何將文件安裝爲默認文件。對於刪除所有導入文件並重新選擇您認爲適用的文件,類似的錯誤可能是值得的。祝你好運!

相關問題