Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
时间: 2023-12-01 14:41:19 浏览: 113
Caused by: android.system.ErrnoException: write failed: ENOSPC (
这个错误通常是由于在Activity的生命周期函数还没有执行完毕时,就尝试在PopupWindow或Dialog中添加窗口导致的。具体来说,可能是在Activity的onCreate函数中尝试添加PopupWindow或Dialog,而此时Activity的生命周期函数还没有执行完毕,所以无法获取到正确的Window Token。解决方法是将PopupWindow或Dialog的添加操作放到Activity的onWindowFocusChanged函数中,这个函数会在Activity的生命周期函数全部执行完毕之后被调用,此时就可以获取到正确的Window Token了。
以下是一个示例代码:
```java
public class MainActivity extends AppCompatActivity {
private Button mButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = findViewById(R.id.button);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
// 在这里添加PopupWindow或Dialog
PopupWindow popupWindow = new PopupWindow(this);
View contentView = LayoutInflater.from(this).inflate(R.layout.popup_window, null);
popupWindow.setContentView(contentView);
popupWindow.showAsDropDown(mButton);
}
}
}
```
阅读全文