Reputation: 135
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());
}
Upvotes: 1
Views: 712
Reputation: 16
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);
Upvotes: 0
Reputation: 135
button.setOnClickListener(v -> {
constraintLayout.setVisibility(View.VISIBLE);
Handler handler = new Handler();
handler.postDelayed(() -> {
scrollView.smoothScrollTo(0, constraintLayout.getBottom());
}, 100);
}
I just figured out this works, but I was hoping to not use a delay.
Upvotes: 1