Detecting completely visible views at runtime

During Development days, we often come across different challenges, one such challenge which I encountered was to detecting Completely visible Views at runtime inside Nested Scrollview. Unlike Recycler view – Layout Manager which has a method of finding completely Visible Views (findFirstCompletelyVisibleItemPosition(), findLastCompletelyVisibleItemPosition()), I had to put in my own logic for Nested Scrollview. Let’s have a look at it:

private void initializeViews() {
        mLinearLayout = findViewById(R.id.container);
        mCustomizedNestedScrollView = findViewById(R.id.nestedScrollview);
        Rect rect = new Rect();
        mCustomizedNestedScrollView.getHitRect(mRect);
    }

In the above method initializeViews(), LinearLayout is the parent Container which contains all the child views and LinearLayout is placed inside NestedScrollView. This is one such example, you can even think of finding child views inside parent RecyclerView. We have set the tag in the XML file to uniquely identify each view. This can be done dynamically when the data is available.

We created a Rect object of type Android.graphics and used the method getHitRect(mRect) which initialize the coordinates of Scrollview to this Rect Object.

 private void findCompletelyVisibleChildren() {
        for (int i = 0; i < mLinearLayout.getChildCount(); i++) {
            View view = mLinearLayout.getChildAt(i);
            if (view != null) {
                if (!view.getLocalVisibleRect(mRect) || mRect.height() < view.getHeight()) {
                    Log.d(TAG, "View " + view.getTag() + " is Partially Visible");
                } else {
                    Log.d(TAG, "View " + view.getTag() + " is Completely Visible");
                }
            }
        }
    }

In the above method, view.getLocalVisibleRect(mRect) returns true if the view is completely visible on the screen.

Hence by following the above steps it helps in detecting completely visible views at runtime inside any parent container.

A simple example is demonstrated here.