0

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

Community
  • 1
  • 1
Pradeep
  • 6,303
  • 9
  • 36
  • 60
  • Why can't you use View.getParent() coupled with onInflate and onAttachToWindow for knowing when to get it? – JohanShogun Aug 10 '15 at 20:01
  • What if direct parent is not Scroll View, CustomView could be inside deep in the View Hierarchy – Pradeep Aug 10 '15 at 20:09
  • I could use recursive function to detect ScrollView using getParent and instance of function, thanks for pointing out @JohanShogun – Pradeep Aug 10 '15 at 20:24

1 Answers1

1

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);
    }
}
Pavel Dudka
  • 20,754
  • 7
  • 70
  • 83
  • 1
    Is there any way to detect, how much portion is visible, like % ? – Pradeep Aug 10 '15 at 20:51
  • @pradeep, sure. If `getGlobalVisibleRect` returns `true`, tempR will hold the visible portion of the view (in global coordinates). So you just compare `tempR.height()` and `getHight()` to calculate visible percentage – Pavel Dudka Aug 10 '15 at 20:53
  • Wow, one more question, Does it consider z order of the views, if some view is overlapping the CustomView, would it return true of false, Thanks a lot @Pavel – Pradeep Aug 10 '15 at 20:59
  • @pradeep it does. If your custom view is fully covered by other views - it returns `false`. If at least small part of your view is visible - its gonna be `true` – Pavel Dudka Aug 10 '15 at 21:06