Same issue as ScrollView .scrollTo not working? Saving ScrollView position on rotation
I dynamically add items to scrollView in onCreate. I try the following after all items were added:
// no effect
ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);
// no effect
ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);
mainScroll.post(new Runnable() {
public void run(){
ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);
mainScroll.scrollTo(0, 0);
}
});
// works like a charm
ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);
mainScroll.postDelayed(new Runnable() {
public void run(){
ScrollView mainScroll = (ScrollView) findViewById(R.id.average_scroll_mainScroll);
mainScroll.scrollTo(0, 0);
}
}, 30);
I conclude that there is some event like 'DOM-ready'? Are there any callbacks?
When you do some changes to a ScrollView, it takes a while for it to replicate the layout changes to the display list and notify the ScrollView that it is, indeed, allowed to scroll to a position.
I've managed to get it working by extending
ScrollView
with a ScrollView of my own, and adding a method that adds theOnGlobalLayoutListener
(as suggested by MH) as needed and scrolls there later. It's a bit more automated than applying it to every case you need it (but then you need to use the newScrollView
). Anyway, this is the relevant code:Very useful for me since I wanted to scroll to a given View inside a ScrollView right after having added it.
You don't need to extend the ScrollView and create your own as per the answer provided by David Daudelin for the this question.
Get the
ViewTreeObserver
of theScrollView
and add anOnGlobalLayoutListener
to theViewTreeObserver
. Then call theScrollView.scrollTo(x,y)
method from theonGlobalLayout()
method of theOnGlobalLayoutListener
. Code:This works for me, replace
scrollView.scrollTo()
toI was helped by Vasily Kabunov 's answer in
ScrollView .scrollTo not working? Saving ScrollView position on rotation