在日常开发中时常会需要判断某个view是否显示,常用的无非就两种:
view.getVisibility()
view.isShown()
这两种方式有没有区别呢?当然有。
结论:前者只返回view本身的visibility,后者返回view本身visibility与它ancestors的visibility综合之后的结果。
看例子:
<LinearLayout
android:id="@+id/llParent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/dialog_btn_txt_color"
android:orientation="vertical"
android:padding="@dimen/activity_horizontal_margin">
<TextView
android:id="@+id/txtChild"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@color/gray"
android:padding="@dimen/activity_horizontal_margin"
android:text="child" />
</LinearLayout>
代码都简单的很,不贴了,直接看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()。