What's the best way to check if the view is visible on the window?

bhups picture bhups · Sep 4, 2010 · Viewed 22.7k times · Source

What's the best way to check if the view is visible on the window?

I have a CustomView which is part of my SDK and anybody can add CustomView to their layouts. My CustomView is taking some actions when it is visible to the user periodically. So if view becomes invisible to the user then it needs to stop the timer and when it becomes visible again it should restart its course.

But unfortunately there is no certain way of checking if my CustomView becomes visible or invisible to the user. There are few things that I can check and listen to:

onVisibilityChange //it is for view's visibility change, and is introduced in new API 8 version so has backward compatibility issue
onWindowVisibilityChange //but my CustomView can be part of a ViewFlipper's Views so it can pose issues
onDetachedFromWindows //this not as useful
onWindowFocusChanged //Again my CustomView can be part of ViewFlipper's views.
So if anybody has faced this kind of issues please throw some light.

Answer

goRGon picture goRGon · Jan 7, 2015

In my case the following code works the best to listen if the View is visible or not:

@Override
protected void onWindowVisibilityChanged(int visibility) {
    super.onWindowVisibilityChanged(visibility);
    Log.e(TAG, "is view visible?: " + (visibility == View.VISIBLE));
}