如何修复在Android中使用Dialog时无法添加窗口

时间:2018-04-03 16:57:01

标签: java android android-dialog

在我的应用程序中,我想使用dialog,为此我应将自定义视图设置为dialog
我在下面编写代码,但在运行应用程序时,在 LogCat 上显示 ForceClose 错误。

我的代码:

   if (!isPremium) {
        count = prefsUtils.getFromShared_INT(PrefsKeys.TRIAL_COUNT.name());
        prefsUtils.setToShared_INT(PrefsKeys.TRIAL_COUNT.name(), count + 1);
        if (count > 10) {
            final Dialog dialog = new Dialog(getApplicationContext());
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.dialog_end_trial);
            TextView dialogEndCount_premiumTxt = dialog.findViewById(R.id.dialogEndCount_premiumTxt);
            dialogEndCount_premiumTxt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, MainActivity2.class);
                    startActivity(intent);
                    finish();
                    dialog.dismiss();
                }
            });
            dialog.show();
        }
    }

LogCat上的错误消息:

 Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
    at android.view.ViewRootImpl.setView(ViewRootImpl.java:702)
    at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:342)
    at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
    at android.app.Dialog.show(Dialog.java:337)
    at com.mcc.wpnews.activity.PostDetailsActivity.initView(PostDetailsActivity.java:176)
    at com.mcc.wpnews.activity.PostDetailsActivity.onCreate(PostDetailsActivity.java:104)
    at android.app.Activity.performCreate(Activity.java:6754)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2679)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2787) 
    at android.app.ActivityThread.-wrap12(ActivityThread.java) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1504) 
    at android.os.Handler.dispatchMessage(Handler.java:102) 
    at android.os.Looper.loop(Looper.java:154) 
    at android.app.ActivityThread.main(ActivityThread.java:6247) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:872) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:762) 

我该如何解决?

1 个答案:

答案 0 :(得分:0)

除非您知道为什么使用getApplicationContext(),否则请勿使用getApplicationContext()

您无法使用Dialog展示Application。因此,将new Dialog(getApplicationContext())替换为new Dialog(this),您应该会有更好的运气。

有关何时使用不同类型Context的详细信息,请参阅this classic blog post from Dave Smith