3

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.

Reinherd
  • 5,476
  • 7
  • 51
  • 88

4 Answers4

7

You could use scrollTo and scroll it by getting the y bottom coordinate divided by 2.

myScrollView.scrollTo(0, myScrollView.getBottom()/2);

For an horizontal scroll view :

myScrollView.scrollTo(widthOfScrollView/2, 0);
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • 1
    I'm looking for HorizontalScrollView. This is for a vertical. – Reinherd Sep 24 '13 at 14:09
  • @SergiCastellsaguéMillán You can also use scrollTo but with `getRight()` on the x coordinate. Does it works ? – Alexis C. Sep 24 '13 at 14:15
  • 1
    No. This is my code `HorizontalScrollView scrollViewSplash = (HorizontalScrollView) this.findViewById(R.id.scrollViewSplash); scrollViewSplash.scrollTo(scrollViewSplash.getRight()/2, 0);` – Reinherd Sep 24 '13 at 14:25
  • May look a this post http://stackoverflow.com/questions/7635903/get-maximum-horizontalscrollview-scroll-amount and try to get the width of the scroll view. – Alexis C. Sep 24 '13 at 14:28
3

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)
    }
})
Cassie
  • 5,223
  • 3
  • 22
  • 34
2
ViewTreeObserver vto = scroll.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    public void onGlobalLayout() {
         scroll.scrollTo(scroll.getChildAt(0).getWidth()/2, 0);
    }
});

This is working!

Reinherd
  • 5,476
  • 7
  • 51
  • 88
1

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) } }

scottt
  • 8,301
  • 1
  • 31
  • 41