Android Visibility与isShown

在日常开发中时常会需要判断某个view是否显示,常用的无非就两种:

view.getVisibility()
view.isShown()

这两种方式有没有区别呢?当然有。
结论:前者只返回view本身的visibility,后者返回view本身visibility与它ancestors的visibility综合之后的结果。
看例子:

    

        
    

代码都简单的很,不贴了,直接看log吧。

E/Visibility: llParent.getVisibility() --> INVISIBLE
E/Visibility: llParent.isShown() --> false
E/Visibility: txtChild.getVisibility() --> VISIBLE
E/Visibility: txtChild.isShown() --> false
E/Visibility: llParent.getVisibility() --> INVISIBLE
E/Visibility: llParent.isShown() --> false
E/Visibility: txtChild.getVisibility() --> INVISIBLE
E/Visibility: txtChild.isShown() --> false

parent是INVISIBLE的,不管child的Visibility如何变化,txtChild.isShown()都返回false。

E/Visibility: llParent.getVisibility() --> VISIBLE
E/Visibility: llParent.isShown() --> true
E/Visibility: txtChild.getVisibility() --> VISIBLE
E/Visibility: txtChild.isShown() --> true
E/Visibility: llParent.getVisibility() --> VISIBLE
E/Visibility: llParent.isShown() --> true
E/Visibility: txtChild.getVisibility() --> INVISIBLE
E/Visibility: txtChild.isShown() --> false

parent和child都是VISIBLE的, txtChild.isShown()才返回true。
总结成一句话就是,要判断用户能否看见某个view,应使用isShown()。

你可能感兴趣的:(Android Visibility与isShown)