android中View的GONE和INVISIBLE的原理

tech2022-12-14  109

GONE真的隐藏;

INVISIBLE不可见但是预留了View的位置;

网上千篇一律的重复着这两句话并举着例子,并没有观察本质来作区分。查看源码后得知其区别希望广大朋友能够借鉴,源码如下:

/* Check if the GONE bit has changed */ if ((changed & GONE) != 0) { needGlobalAttributesUpdate(false); requestLayout(); if (((mViewFlags & VISIBILITY_MASK) == GONE)) { if (hasFocus()) { clearFocus(); if (mParent instanceof ViewGroup) { ((ViewGroup) mParent).clearFocusedInCluster(); } } clearAccessibilityFocus(); destroyDrawingCache(); if (mParent instanceof View) { // GONE views noop invalidation, so invalidate the parent ((View) mParent).invalidate(true); } // Mark the view drawn to ensure that it gets invalidated properly the next // time it is visible and gets invalidated mPrivateFlags |= PFLAG_DRAWN; } if (mAttachInfo != null) { mAttachInfo.mViewVisibilityChanged = true; } } /* Check if the VISIBLE bit has changed */ if ((changed & INVISIBLE) != 0) { needGlobalAttributesUpdate(false); /* * If this view is becoming invisible, set the DRAWN flag so that * the next invalidate() will not be skipped. */ mPrivateFlags |= PFLAG_DRAWN; if (((mViewFlags & VISIBILITY_MASK) == INVISIBLE)) { // root view becoming invisible shouldn't clear focus and accessibility focus if (getRootView() != this) { if (hasFocus()) { clearFocus(); if (mParent instanceof ViewGroup) { ((ViewGroup) mParent).clearFocusedInCluster(); } } clearAccessibilityFocus(); } } if (mAttachInfo != null) { mAttachInfo.mViewVisibilityChanged = true; } }

如果在GONE和INVISIBLE两者都可以完成你的效果,那么你应该选择INVISIBLE。因为从源码中来看GONE需要重新的布局和通知上级View去刷新,有缓存还要清空缓存;从视图变更开销的来说INVISIBLE要更加的划算一些,如果你的View不是十分占用资源的情况!!!

最新回复(0)