窗口管理器,$ BadTokenException Android中管理器、窗口、Android、BadTokenException

2023-09-06 23:53:12 作者:曾经撕心裂肺如今百毒不侵

首先,我很清楚地知道,这个错误发生,因为我想通过上下文这不是一个活动。

First of all, I'm well aware that this error is occur because I'm trying to call window/dialog through a Context that is not an Activity.

不过,是不是有什么方法解决了。我的要求是;我有一个对话框在一个普通的Java类的方法的自定义样式表。我想调用该方法从任何活动上课的时候​​我需要加载对话框

But isn't there any solution to that. My requirements are; I have a Dialog with a custom style sheet in a method of a normal JAVA class. I want to call that method from any Activity class when I need to load the Dialog.

在我的Activity类我有以下的code组;

In my Activity class I'm having following code set;

HomeClass homeClass = new HomeClass();
homeClass.showSplashScreen();

然后在我的HomeClass我有以下code组;

Then in my HomeClass I have following code set;

public void showSplashScreen() {        
 splashDialog = new Dialog(HomeActivity.getAppContext(), R.style.SplashScreen);
 splashDialog.setContentView(R.layout.splash_screen);
 splashDialog.setCancelable(false);
 splashDialog.show();
}

通过维持这样的设计,有没有什么办法来摆脱窗口管理器,$ BadTokenException

感谢您

推荐答案

我要修改code,也许对你有帮助...

I am going to modify your code, that maybe helpful for you...

HomeClass homeClass = new HomeClass(this);
homeClass.showSplashScreen();

在您的家类..添加参数的构造函数。

In Your Home class.. add parametric constructor..

public class Home {
private Context context;
public Home(Context context){
this.context = context;
}
public void showSplashScreen() {        
splashDialog = new Dialog(context, R.style.SplashScreen);
 splashDialog.setContentView(R.layout.splash_screen);
 splashDialog.setCancelable(false);
splashDialog.show();
}