Search code examples
androidscrollviewcenterlocked

Cannot center buttons inside ScrollView properly


I saw this question asked everywhere but I think each case has its own resolution. What I have is this:

<HorizontalScrollView
    android:id="@+id/MenuScroll"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:fillViewport="true"
    android:scrollbars="none" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:orientation="horizontal"
            android:layout_gravity="center"
        android:padding="0dp" >

        <Button
            android:layout_width="150dp"
            android:layout_height="fill_parent" />

        <Button
            android:layout_width="150dp"
            android:layout_height="fill_parent" />

        <Button
            android:layout_width="150dp"
            android:layout_height="fill_parent" />

        <Button
            android:layout_width="150dp"
            android:layout_height="fill_parent" />

        <Button
            android:layout_width="150dp"
            android:layout_height="fill_parent" />

    </LinearLayout>
</HorizontalScrollView>

and what I pretend is having the LinearLayout centered inside the HorizontalScrollView. It is centered (I see halfbutton - button - halfbutton) but I can't scroll to the first button. Looks like the space occupied by the content hidden to the left is added at the right and some space is added after the HorizontalScrollView. enter image description here

Is there any solution, even if I have to do it dynamically?


Solution

  • I had this same problem, to avoid it just remove

     android:layout_gravity="center"
    

    from

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="48dp"
        android:orientation="horizontal"
            android:layout_gravity="center"
        android:padding="0dp" >
    

    You can add a timer while creating the layout view to scroll properly. If you don't add the timer, it won't scroll due to the view not being created. You can't scroll something it can't be seen yet

     new Timer().schedule(new TimerTask () {
            @Override
            public void run() {
                //SOME SCROLLING FUNCTION
                }}, 50);