How and why to use Android Visibility Listeners

tomerpacific
We’ve moved to freeCodeCamp.org/news
3 min readDec 27, 2018
“woman holding string lights” by Rhett Wesley on Unsplash

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:

  1. Your View is already part of your layout as it is defined in an XML file
  2. You created a View dynamically, and you need to add it using the addView method
child is the View you want to add and LayoutParams are the layout parameters(I.E. width, and height)

A View’s visibility status is of Integer type and can have one of three options:

  1. VISIBLE (0) - The View is visible to the user
  2. INVISIBLE (4) - The View is invisible to the user, but still takes up space in the layout
  3. 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.

onVisibilityChanged

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.

onWindowVisibilityChanged

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:

We attach an OnClick Listener to the button

When we run the application and press the button we get:

You can see inside Logcat that the listeners are called when our view comes into view

You can get the sample project here.

ViewTreeObserver

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:

removeOnGlobalLayoutListener requires API > 15

The line 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! 👏

--

--