源码解析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()。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容