gpt4 book ai didi

android - PopupWindow 抛出 BadTokenException

转载 作者:太空狗 更新时间:2023-10-29 14:55:24 24 4
gpt4 key购买 nike

如果我直接在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);

}

请帮助我理解它。

最佳答案

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

关于android - PopupWindow 抛出 BadTokenException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32002654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com