gpt4 book ai didi

java - 安卓.view.WindowManager$BadTokenException : Unable to add window — token null is not valid

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:32:58 25 4
gpt4 key购买 nike

每当我尝试启动我的窗口类时,我都会收到此错误。我正在使用单独的类,而不仅仅是我的游戏类中的一个方法,因为我需要禁用该弹出窗口上的后退按钮。我用一个按钮调用这个类。如果我在我的游戏类中使用此代码,但在单独的类中不使用,则此代码可以正常工作。这是我的代码:

public class Popup_pogresno extends Activity implements OnClickListener{

private PopupWindow pwindow;

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

LayoutInflater layoutInflater
= (LayoutInflater)Popup_pogresno.this
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
pwindow = new PopupWindow(popupView, 300, 170, true);

Button btnDismiss = (Button)popupView.findViewById(R.id.bPopupOK);
btnDismiss.setOnClickListener(new Button.OnClickListener(){

public void onClick(View v) {
// TODO Auto-generated method stub
pwindow.dismiss();
}});

pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);

}

public void onClick(View v) {
// TODO Auto-generated method stub

}
@Override
public void onBackPressed() {

}
}

最佳答案

您没有在 onCreate(Bundle) 方法中调用 setContentView(R.layout.myLayout)。在 super.onCreate(savedInstanceState); 之后立即调用它。

这是来自 Android 开发者网站上的 Activity 资源页面:

There are two methods almost all subclasses of Activity will implement:

onCreate(Bundle) is where you initialize your activity. Most importantly, here you will usually call setContentView(int) with a layout resource defining your UI, and using findViewById(int) to retrieve the widgets in that UI that you need to interact with programmatically.

onPause() is where you deal with the user leaving your activity. Most importantly, any changes made by the user should at this point be committed (usually to the ContentProvider holding the data).

编辑 1:

替换:

pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);

与:

new Handler().postDelayed(new Runnable(){

public void run() {
pwindow.showAtLocation(popupView, Gravity.CENTER, 0, 0);
}

}, 100L);

关于java - 安卓.view.WindowManager$BadTokenException : Unable to add window — token null is not valid,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17787011/

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