You have to subclass the view you want to add a listener to. You then should override onVisibilityChanged instead of setVisibility. onVisibilityChanged is triggered when the view's visibility is changed for any reason, including when an ancestor view was changed.
You will need an interface if you want a different class to be notified when your View's visibility changes.
Example:
public class MyView extends View {
private OnVisibilityChangedListener mVisibilityListener;
public interface OnVisibilityChangedListener {
// Avoid "onVisibilityChanged" name because it's a View method
public void visibilityChanged(int visibility);
}
public void setVisibilityListener(OnVisibilityChangedListener listener) {
this.mVisibilityListener = listener;
}
protected void onVisibilityChanged (View view, int visibility) {
super.onVisibilityChanged(view, visibility);
// if view == this then this view was directly changed.
// Otherwise, it was an ancestor that was changed.
// Notify external listener
if (mVisibilityListener != null)
mVisibilityListener.visibilityChanged(visibility);
// Now we can do some things of our own down here
// ...
}
}