Search code examples
androidandroid-fragmentsandroid-scrollview

How to check a view in fragment is appearing in the current window or it's out of the current window?


I have a scroll view and text view inside it, I want to know whether it's gone out of the window or it's still inside the window.

scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                @Override
                public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                    L.e(" isShown " + textView.isShown());
                }
            });

Thanks in advance.


Solution

  • Use the below code. it's perfectly working for me

    if (scrollView != null) {
           if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
               Rect scrollBounds = new Rect();
               scrollView.getHitRect(scrollBounds);
               scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
                   @Override
                   public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                       String title = "your title";
                       if (view != null) {
                           if (view.getLocalVisibleRect(scrollBounds)) {
                               setPageTitle("");
                           } else {
                               setPageTitle(title == null ? "" : title);
                           }
                       }
                   }
               });
           }
       }