android View.isShown() 和 getVisibility() 的區別

有時候,我們會判斷當前我們的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 也是可見的。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章