Andorid

源码解析view的显示判断用isShown()还是View.VI

2019-10-18  本文已影响0人  萨达哈鲁酱

前言

平时我们对View的显示判断都是用简要的方式去判断,那么,究竟是用view.isShown()去判断还是用view.
getVisibility() == View.VISIBLE 判断好呢?其实可以来看看源码


源码

/**
     * 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。

 /**
     * 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()。

上一篇 下一篇

猜你喜欢

热点阅读