2014-10-18 33 views
1

當我的應用程序運行時,出現此錯誤: 「android.view.WindowManager $ BadTokenException:無法添加窗口 - 標記null無效;您的活動正在運行嗎?」PopupWindow BadTokenException錯誤

我的代碼是:

LayoutInflater layoutInflater = (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE); 
View popupView = layoutInflater.inflate(R.layout.nextround_popup, parent, false); 
final PopupWindow popupWindow = new PopupWindow(popupView,(int) (width * .6), (int) (height * .8)); 
Button btnDismiss = (Button)popupView.findViewById(R.id.dismiss); 
popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.black_gradient)); 
new Handler().postDelayed(new Runnable(){ 
    public void run() { 
     popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0); 
    } 
}, 100L);   

我搜索的話,我找到了一些解決方案,但我沒把它解決了。任何幫助,將不勝感激,因爲這是frastruating :)先進

回答

1

此錯誤的原因

由於是PopupWindow表現需要一個令牌,但該視圖不會有令牌,直到活動渲染完成。即使你延遲了。以及100毫秒是短暫的,但如果使它更長,似乎是愚蠢的。 你可以在onWindowFocusChanged方法中顯示PopupWindow,當Activity渲染完成時,這個方法會被調用。如下所示:

class MyActivity extends Activity{ 
//... 
@Override 
public void onWindowFocusChanged(boolean hasFocus){ 
if(hasFocus){ 
//show your PopupWindow 
popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0); 
} 
} 

//... 
} 
相關問題