The Android UI is built up from Views, and in a regular application, there are usually several of them. To find out which View the user is currently looking at, you need to install Visibility Listeners.
Read below to find out about the different options you have to identify the visibility status of a View.
How To Become Visible
In order for our listeners to work, we must first make sure our View is found in the layout hierarchy. There are two ways this happens:
- Your View is already part of your layout as it is defined in an XML file
- You created a View dynamically, and you need to add it using the addView method
A View’s visibility status is of Integer type and can have one of three options:
- VISIBLE (0) - The View is visible to the user
- INVISIBLE (4) - The View is invisible to the user, but still takes up space in the layout
- GONE (8) - The View is invisible, and it does not take up space in the layout
Once inside our layout hierarchy, there are a few native options to help us know when our View’s visibility has changed.
This method is triggered when the visibility of the view or of an ancestor of the view has changed. The status of the visibility is found inside the visibility parameter.
This method is triggered when the containing window of our View has changed its visibility. This does not guarantee that the window your View is in is visible to the user, as it may be obscured by another window.
Visibility Listeners In Action
To see these two listeners in action, let us create a simple project. We will have a LinearLayout with a TextView and a button. We’ll make the button’s on click action add our custom view to the layout.
Our custom view:
And finally, the code in our MainActivity:
When we run the application and press the button we get:
You can get the sample project here.
This is a native object that has a wide range of listeners that are notified of various visibility changes to the view tree. Some prominent ones to take notice of are:
To attach a ViewTreeObserver, you need to do the following:
linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this) makes sure that the listener will only get called once. If you want to continue listening in on changes, remove it.
If you have any comments or suggestions, feel free to let me know.
If you liked this article, clap away so that others can enjoy it as well! 👏