Search code examples
javaandroidscrollviewhorizontalscrollviewscrollto

Android Studio: scrollTo in Horizontal function isn't working


I'm making this converter app and have spent some time trying to figure out how to work this scrollTo() function to scroll to the button I desire it to be focused in a Horizontal Scroll View.

I've implemented the following to my onCreate:

        final HorizontalScrollView HscrollView1 = (HorizontalScrollView)findViewById(R.id.hsView1);
        final HorizontalScrollView HscrollView2 = (HorizontalScrollView)findViewById(R.id.hsView2);

        final Button cmBtn = (Button)findViewById(R.id.cm_id);
        final Button KmBtn = (Button)findViewById(R.id.km_id);
        final Button mmBtn = (Button)findViewById(R.id.mm_id);

        HscrollView1.scrollTo((int) mmBtn.getX(), 0);
        HscrollView2.scrollTo((int) cmBtn.getX(), 0);

After running APK, it won't scroll to mm and cm button when the app starts (unlike what I wrote in the code)

It seems so frustrating to me with this scrollview and it would be awesome if someone can help me here at 5am (est)

Thank you!


Solution

  • replace

        HscrollView1.scrollTo((int) mmBtn.getX(), 0);
        HscrollView2.scrollTo((int) cmBtn.getX(), 0);
    

    with

    new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        HscrollView1.scrollTo((int) mmBtn.getX(), 0);
                        HscrollView2.scrollTo((int) cmBtn.getX(), 0);
                    }
                }, 500);
    

    and run your code.