源碼解析view的顯示判斷用isShown()還是View.VISIBLE

前言

平時我們對View的顯示判斷都是用簡要的方式去判斷,那麼,究竟是用view.isShown()去判斷還是用view.
getVisibility() == View.VISIBLE 判斷好呢?其實可以來看看源碼


源碼

  • isShow()
/**
     * 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;
            if (parent == null) {
                return false; // We are not attached to the view root
            }
            if (!(parent instanceof View)) {
                return true;
            }
            current = (View) parent;
        } while (current != null);

        return false;
    }

可以看出註釋
只有當view本身以及它的所有祖先們都是visible時,isShown()才返回TRUE。

  • View.VISIBLE
 /**
     * This view is visible.
     * Use with {@link #setVisibility} and <a href="#attr_android:visibility">{@code
     * android:visibility}.
     */
    public static final int VISIBLE = 0x00000000;

而平常我們調用if(view.getVisibility() == View.VISIBLE)只是對view本身而不對祖先的可見性進行判斷。


總結

其實精煉總結成一句話就是,要判斷用戶能否看見某個view,應使用isShown()。

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