当我的应用程序运行时,我收到此错误: " android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null无效;你的活动在运行吗?"
我的代码是:
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);
我搜索了SO,我找到了一些解决方案,但我没有设法解决它。任何帮助将不胜感激,因为这是frastruating:)
先谢谢
答案 0 :(得分:1)
此错误的原因是PopupWindow显示需要一个令牌,但在Activity呈现完成之前,视图将不会有令牌。即使你让它延迟了。以及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);
}
}
//...
}