有时候,我们会判断当前我们的View 是否可见。
常见的判断如:

View.getVisibility() == View.VISIBLE

还有一种是

View.isShown().

这两种有什么区别呢?我们看下的源码:

getVisibility 源码:

    @Visibility
    public int getVisibility() {
        return mViewFlags & VISIBILITY_MASK;
    }

isShown 源码:

    /**
     * Returns the visibility of this view and all of its ancestors
     *
     * @return True if this view and all of its ancestors are {@link #VISIBLE}
     */
    public boolean isShown() {
        View current = this;
        //noinspection ConstantConditions
        do {
        	
            if ((current.mViewFlags & VISIBILITY_MASK) != VISIBLE) {
                return false;
            }
            ViewParent parent = current.mParent;
            // 如果parent 是null 说明并没有连接到view root
            if (parent == null) {
                return false; // We are not attached to the view root
            }
            //最终的ViewParenet 是ViewRootImpl, 会走到这里,返回true
            if (!(parent instanceof View)) {
                return true;
            }
            current = (View) parent;
        } while (current != null);

        return false;
    }

我们看到getVisibility 只是查看了一下当前view 的flag,返回结果。

而isShown 方法会先判断当前View 的flag, 然后循环拿到父View,判断是不是可见。只要有一个是不可见的,那么isShown就返回false.

所以,区别就是:

getVisibility 只会判断当前View 是不是可见。isShown 会判断当前View 可见,并且所有的View 树上的parent 也是可见的。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐