Search code examples
androidhorizontal-scrollinghorizontalscrollview

How to programmatically scroll an HorizontalScrollView


I have an HorizontalScrollView which contains a RelativeLayout. This layout is empty in the XML, and is populated from java in the onCreate.

I would like this scroll view to be initially somewhere in the middle of the RelativeLayout, which is way larger than the screen.

I tried mHorizScrollView.scrollTo(offsetX, 0); which doesn't work. I don't know what's wrong with this.

I could post the code, but it is not really relevant. What matters is that everything is done programatically (has to :s), and that the initial position of the HorizontalScrollView has to be set programmatically.

Thanks for reading. Please tell me if you need more details or if this is not clear enough.


Solution

  • I found that if you extend the HorizontalScrollView and override the onLayout, you can cleanly scroll, after the super call to onLayout:

    MyScrollView extends HorizontalScrollView {
        protected void onLayout (boolean changed, int l, int t, int r, int b) {
            super.onLayout(changed, l, t, r, b);
            this.scrollTo(wherever, 0);
        }
    }
    

    EDIT: For scrolling to start or end you can use:

    this.fullScroll(HorizontalScrollView.FOCUS_RIGHT/FOCUS_LEFT);
    

    instead of

    this.scrollTo(wherever, 0);