Center content in scroll view

Egis picture Egis · Oct 23, 2013 · Viewed 26k times · Source

I want to center my LinearLayout within ScrollView. When LinearLayout's height is small it's centered alright (see image #1) but when LinearLayout's height is bigger than the screen's height then it behaves strange. I cannot see the top of LinearLayout (see image #2) and at the bottom of ScrollView there's huge padding. I don't know what's happening here. When there are lots of content in LinearLayout the whole screen should look like in image #3.

image #1
image #2
image #3

Here's my layout file:

            <?xml version="1.0" encoding="utf-8"?>
            <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:background="#cccfff" >

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center_vertical"
                    android:layout_margin="28dp"
                    android:background="#ffffff"
                    android:orientation="vertical"
                    android:paddingBottom="40dp"
                    android:paddingLeft="20dp"
                    android:paddingRight="20dp"
                    android:paddingTop="40dp" >

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="16dp"
                        android:src="@drawable/ic_launcher" />

                    <TextView
                        android:id="@+id/tip_title"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginBottom="12dp"
                        android:text="Title"
                        android:textColor="@color/orange_text"
                        android:textSize="@dimen/font_size_medium" />

                    <TextView
                        android:id="@+id/tip_description"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Description description..."
                        android:textSize="@dimen/font_size_small" />
                </LinearLayout>

            </ScrollView>

Answer

yaircarreno picture yaircarreno · Nov 12, 2015

You can use android:fillViewport="true" to center the content. Something like this:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true">
        <!-- content -->
</ScrollView>