Search code examples
androidandroid-linearlayoutcenteringandroid-scrollview

Android ScrollView not centering


I have the following code:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">
    <ScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/activity_list_films">

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Back"
                android:onClick="back"/>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

However the button, and the stuff that I add to the inner LinearLayout dynamically, all appear on the top left of the screen. What am I doing wrong?

I have tried putting layout_gravity="center" and gravity="center" in the inner LinearLayout too, but this does not help.

Thanks.


Solution

  • Your LinearLayout width is wrap_content : it doesn't take the whole width of the screen and cannot center content horizontally. So change it to android:layout_width="match_parent" also set layout_gravity to center_horizontal android:layout_gravity="center_horizontal"

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center">
    
        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <LinearLayout
                android:id="@+id/activity_list_films"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
    
                <Button
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_horizontal"
                    android:onClick="back"
                    android:text="Back" />
            </LinearLayout>
        </ScrollView>
    </LinearLayout>