Reputation: 5506
I'm trying to scroll in Android a HorizontalScrollView programmatically.
However I just found this method:
scroll.fullScroll(View.FOCUS_DOWN)
And I'm looking forward to scroll the view to exactly the middle.
Any tip?
I know that there's a method to scroll to an exact position:
setScrollX
but the parameter should be calculated somehow I don't know.
Upvotes: 3
Views: 6643
Reputation: 8371
Here's an easy way to do it in Kotlin without using a OnGlobalLayoutListener, where wideView is the view within the ScrollView.
wideView.apply { post { scrollView.scrollTo((left + right - scrollView.width) / 2, 0) } }
Upvotes: 1
Reputation: 5243
This is an old question but I found the other answers didn't work for me. The following worked well.
val vto = viewTreeObserver
vto.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
val maxScroll = scrollView.getChildAt(0).width - scrollView.width
scrollView.scrollTo(maxScroll / 2, 0)
viewTreeObserver.removeOnGlobalLayoutListener(this)
}
})
Upvotes: 3
Reputation: 5506
ViewTreeObserver vto = scroll.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
public void onGlobalLayout() {
scroll.scrollTo(scroll.getChildAt(0).getWidth()/2, 0);
}
});
This is working!
Upvotes: 2