2012-02-26 35 views
0

我知道這個問題在stackoverflow上被問了很多次,但我無法找到可以解決我的問題的答案。WindowLeaked錯誤,同時顯示PopupWindow

這是我從Activity的onPause()函數中調用的代碼。

` 

`protected void onPause() { 
     // TODO Auto-generated method stub 
     super.onPause(); 
     new DialogueTask().execute(this); 
     } 

而且實現對話類的任務是

class DialogueTask extends AsyncTask<Activity, Void, PopupWindow> { 
    private View layout; 

    @Override 
    protected PopupWindow doInBackground(Activity... activities) { 
     LayoutInflater layoutInflater = (LayoutInflater) activities[0] 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     layout = layoutInflater.inflate(R.layout.popup, 
       (ViewGroup) activities[0].findViewById(R.id.popup_id)); 
     PopupWindow pw; 
     pw = new PopupWindow(layout, 100, 100, true); 
     return pw; 
    } 

    @Override 
    protected void onPostExecute(PopupWindow pw) { 
     // TODO Auto-generated method stub 
     pw.showAtLocation(layout, Gravity.CENTER, 0, 0); 
    } 

這是popup.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/popup_id" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="vertical" > 

    <TextView 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_gravity="center_horizontal" 
     android:text="Sure you want to Quit?" > 
    </TextView> 


</LinearLayout> 

當單擊後退按鈕,然後在onPause()被調用,它給WindowLeaked例外。我想,我已經注意到彈出窗口通過實現AsyncTask在UI線程中顯示。那麼問題出在哪裏?

回答

0

彈出窗口活動從主要活動打開,並且您正在退出主要活動而不關閉彈出窗口活動。 pw.dismiss()在pw.showAtLocation(layout,Gravity.CENTER,0 ,0)將解決問題

@Override 
protected void onPostExecute(PopupWindow pw) { 
    // TODO Auto-generated method stub 
    pw.showAtLocation(layout, Gravity.CENTER, 0, 0); 
    pw.dismiss(); 
} 
+1

加上pw.dismiss()彈出窗口不會出現在屏幕上。隨着活動暫停,彈出窗口也會消失。 – 2012-02-26 15:20:38