简体   繁体   中英

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

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);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM