android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid;

今天是在北京隔离的第十四天 ,明天就可以去公司上班了 。

使用 Popupwindow的时候出现的闪退 。

Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
 

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:858)
        at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
        at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
        at android.widget.PopupWindow.invokePopup(PopupWindow.java:1434)
        at android.widget.PopupWindow.showAtLocation(PopupWindow.java:1203)
        at android.widget.PopupWindow.showAtLocation(PopupWindow.java:1170)
        at com.edusoho.kuozhi.cuour.gensee.vod.VodVideoActivity.initData(VodVideoActivity.java:563)
        at com.edusoho.commonlib.base.NewBaseActivity.onCreate(NewBaseActivity.java:63)
        at com.edusoho.kuozhi.cuour.base.BaseToolbarActivity.onCreate(BaseToolbarActivity.java:30)
        at android.app.Activity.performCreate(Activity.java:7224)
        at android.app.Activity.performCreate(Activity.java:7213)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)

原因

由于PopupWindow弹窗不能直接在Activity的onCreate函数里执行,必须要等activity的生命周期函数全部执行完毕之后

解决方案(一)

使用 view.post

    iv_news_icon.post(new Runnable() {
                @Override
                public void run() {
                    View contentView = LayoutInflater.from(mActivity).inflate(R.layout.popup_news_tips, null);
                    popupWindow = new PopupWindow(contentView ,ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                    popupWindow.setBackgroundDrawable(new BitmapDrawable());

                    // 设置弹窗外可点击
                    popupWindow.setOutsideTouchable(true);
                    popupWindow.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setContentView(contentView);

                    popupWindow.showAtLocation(iv_news_icon, Gravity.NO_GRAVITY,0,0);
                }
            });

...

...

...

PS:属于一个小瑕疵。

发布了71 篇原创文章 · 获赞 57 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_37492806/article/details/104638008