Search code examples
android-studiovisibilityandroid-scrollviewvisible

Scroll after view becomes visible


I am trying to scroll to the bottom of my scrollView after a view becomes visible with button click. The problem is the scrollTo function is applied before the view is actually visible. I know this because when the button is pressed twice, it scrolls to the bottom on the second click. So, is there a way to scroll after the view becomes visible?

button.setOnClickListener(v -> {
    constraintLayout.setVisibility(View.VISIBLE);
    scrollView.smoothScrollTo(0, constraintLayout.getBottom());
}

Solution

  • Another option is to use a listener.

    ViewTreeObserver.OnPreDrawListener viewVisibilityChanged = new ViewTreeObserver.OnPreDrawListener() {
        @Override
        public boolean onPreDraw() {
            if (my_view.getVisibility() == View.VISIBLE) {
                scroll_view.smoothScrollTo(0, scroll_view.getHeight());
            }
            return true;
        }
    };
    

    You can add it to your view this way :

    my_view.getViewTreeObserver().addOnPreDrawListener(viewVisibilityChanged);