Search code examples
androidxmlcenteringhorizontalscrollview

android horizontal vertical scroll layout with center


I need create something like this in xml, but it is not possible to center inner object in scrollView with child horizontalScrollView.

here is code example:

<ScrollView
    android:id="@+id/scrollView1"
    android:layout_width="fill_parent"
    android:layout_height="0dp"
    android:layout_weight="5"
    android:fillViewport="true" >

    <HorizontalScrollView
        android:id="@+id/horizontalScrollView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <TableLayout
                android:id="@+id/matrix_table"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true" >

                <!-- auto generated rows -->

            </TableLayout>

        </RelativeLayout>

    </HorizontalScrollView>

</ScrollView>

and here is unexpected result

Thanks!


Solution

  • Setting a child view to fill_parent doesn't work very well in ScrollViews. Instead, you should set the child view dimensions to wrap_content and use layout_gravity :

    <HorizontalScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    
        <TableLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" >
        ...
    
    </HorizontalScrollView>