WindowManager$BadTokenException in Android

2019-02-20 04:34发布

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.

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.

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

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

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();
}

By maintaining this design, is there any way to get rid of the WindowManager$BadTokenException

Thank You

2条回答
forever°为你锁心
2楼-- · 2019-02-20 05:16

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();
}
查看更多
乱世女痞
3楼-- · 2019-02-20 05:19

Pass Your Activity to showSplashScreen() Method...

Do like this..

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

In Your Home class

public void showSplashScreen(Activity curActivity) {        
 splashDialog = new Dialog(curActivity, R.style.SplashScreen);
 splashDialog.setContentView(R.layout.splash_screen);
 splashDialog.setCancelable(false);
 splashDialog.show();
}
查看更多
登录 后发表回答