Reinherd
Reinherd

Reputation: 5506

Scroll ScrollView to middle

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

Answers (4)

scottt
scottt

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

Cassie
Cassie

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

Reinherd
Reinherd

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

Alexis C.
Alexis C.

Reputation: 93842

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

Upvotes: 7

Related Questions