美文网首页
WindowManager$BadTokenException异

WindowManager$BadTokenException异

作者: 萍水相逢_程序员 | 来源:发表于2018-12-05 11:34 被阅读0次

android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?这个错误,

很多通过activity生命周期来进行判断,这个不准确。

看错误,就是token为null,避免错误直接在调用showAtLocation showAsDropDown之前加个判断了,
就能解决了。

看PopupWindow源码:

    public void showAtLocation(View parent, int gravity, int x, int y) {
        mParentRootView = new WeakReference<>(parent.getRootView());
        showAtLocation(parent.getWindowToken(), gravity, x, y);
    }

    public void showAsDropDown(View anchor) {
        showAsDropDown(anchor, 0, 0);
    }

    public void showAsDropDown(View anchor, int xoff, int yoff) {
        showAsDropDown(anchor, xoff, yoff, DEFAULT_ANCHORED_GRAVITY);
    }

   public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {
        if (isShowing() || !hasContentView()) {
            return;
        }

        TransitionManager.endTransitions(mDecorView);

        attachToAnchor(anchor, xoff, yoff, gravity);

        mIsShowing = true;
        mIsDropdown = true;

        final WindowManager.LayoutParams p =
                createPopupLayoutParams(anchor.getApplicationWindowToken());
        preparePopup(p);

        final boolean aboveAnchor = findDropDownPosition(anchor, p, xoff, yoff,
                p.width, p.height, gravity, mAllowScrollingAnchorParent);
        updateAboveAnchor(aboveAnchor);
        p.accessibilityIdOfAnchor = (anchor != null) ? anchor.getAccessibilityViewId() : -1;

        invokePopup(p);
    }

可以在传入对应view之前做个判断了

anchor.getApplicationWindowToken() ,或parent.getWindowToken() 判断是否为null, 不为null就在调用了弹出的方法。

相关文章

网友评论

      本文标题:WindowManager$BadTokenException异

      本文链接:https://www.haomeiwen.com/subject/bryicqtx.html