PopupWindow引发BadTokenException异常

3
如果我直接在oCreate()中添加showPopupWindow();,会出现以下错误:

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?

如下所示:
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
我认为在 onCreate() 方法中显示弹出窗口还为时过早,因为此时活动可能尚未完成所需的生命周期。您需要通过实现几分之一秒的延迟来区分您的解决方案。

我会尝试遵循你的建议。 - xfshipan
我遵循了你的建议,但对我来说没有成功,我将它添加到onCreate()方法中。尝试 { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); }显示弹出窗口(); - xfshipan

0

使用Handler代替Thread.sleep()

Handler handler = new Handler();

然后在setContentView()之后。
handler.postDelayed(new Runnable() 
{   
    @Override
    public void run() 
    {
        showPopupWindow();
    }
}, 2000);

抱歉,请在 setContentView 之后再尝试。 - JLT

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接