PopupWindow抛出BadTokenException

时间:2015-08-14 05:07:34

标签: android

如果我直接在showPopupWindow();添加oCreate(),则会出错:

  

android.view.WindowManager $ BadTokenException:无法添加窗口 - 令牌null无效;你的活动在运行吗?

像这样:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);

    showPopupWindow();
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
             showPopupWindow();
        }
    });
}

private void showPopupWindow() {
    TextView textView = new TextView(this);
    textView.setText("This is a Text");
    textView.setTextSize(20);
    textView.setTextColor(Color.parseColor("#33000000"));
    //悬浮窗体
    popupWindow = new PopupWindow(textView,-2,-2);
    //设置View
    popupWindow.setContentView(textView);
    //设置宽高
    //必须设置背景
    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
    //父窗体,Gravity,位置(x距离左边的距离,y距离上边的距离)
    popupWindow.showAtLocation(findViewById(R.id.rl_main), Gravity.LEFT + Gravity.TOP, 60, 60);

}

但如果我将其添加到onClick中,就可以了,如下:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showPopupWindow();
        }
    });
}

private void showPopupWindow() {
    TextView textView = new TextView(this);
    textView.setText("This is a Text");
    textView.setTextSize(20);
    textView.setTextColor(Color.parseColor("#33000000"));
    //悬浮窗体
    popupWindow = new PopupWindow(textView,-2,-2);
    //设置View
    popupWindow.setContentView(textView);
    //设置宽高
    //必须设置背景
    popupWindow.setBackgroundDrawable(new ColorDrawable(Color.BLUE));
    //父窗体,Gravity,位置(x距离左边的距离,y距离上边的距离)
    popupWindow.showAtLocation(findViewById(R.id.rl_main), Gravity.LEFT + Gravity.TOP, 60, 60);

}

请帮助我理解它。

2 个答案:

答案 0 :(得分:0)

我想说在onCreate()方法中显示弹出窗口为时尚早,因为直到那时,活动可能还没有完成所需的生命周期。您需要通过实现几秒钟的延迟来区分您的解决方案。

答案 1 :(得分:0)

使用处理程序代替Handler handler = new Handler();

handler.postDelayed(new Runnable() 
{   
    @Override
    public void run() 
    {
        showPopupWindow();
    }
}, 2000);

然后在setContentView();

之后
{{1}}