Q:

Detecting visibility of Android View

I am providing CustomView to the Android developer through Android Library project. Inside the Library project, I want to detect whether this view is getting rendered and visible to the User ( By visible I mean viewed by the User). 
I thought of few approaches,
I could override onDraw or dispatchDraw methods to detect when view is drawn on the screen but this doesn't mean the CustomView is viewed by the user.
If View is inside the scrollview, There are ways to detect whether view is visible to the user. This is working but when I have explicit reference to scrollview on which I can add scroll event listener. The only thing I will have access, is context object and initialized reference of CustomView
Since, I am providing my project as jar dependency or jar to the developer, How could I ensure my View is visible to the User 

A:

If you want to know when view is visible at the root level (not covered by another view and not translated out of the screen) there is an API for that available - View#getGlobalVisibleRect (Rect r).
So you still need to override onDraw() method inside your custom view, but you need to keep calling getGlobalVisibleRect in order to get visibility status:
public class CustomView extends View {
    Rect tempR = new Rect();

    @Override protected void onDraw(Canvas canvas) {
        boolean isVisible = getGlobalVisibleRect(tempR);
        //here isVisible flag will be true if at least portion of the view is visible to the user
        super.onDraw(canvas);
    }
}

