Search code examples
javaandroidandroid-viewandroid-scrollviewhorizontalscrollview

setScrollX function doesn't work well


I have some source code for scrolling.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = findViewById(R.id.txtv);
    HorizontalScrollView sv = findViewById(R.id.scroll);

    sv.setScrollX(100);
}

I want to set x scroll position to 100px. But setScrollX function doesn't work well. What's the problem? How should I do?


Solution

  • The problem is, that at that point the actual view is not laid out yet. You have to delay the scrolling until HorizontalScrollView is laid out:

    
        protected void onCreate(Bundle savedInstanceState) {
            ...
            HorizontalScrollView sv = findViewById(R.id.scroll);
            sv.post(new Runnable() {
                @Override
                public void run() {
                    sv.smoothScrollBy(100, 0);
                }
            })
        }