Close
Glad You're Ready. Let's Get Started!

Let us know how we can contact you.

Thank you!

We'll respond shortly.

LABS
Centering a View within a ScrollView

We have a View that we want centered on the screen, but that must scroll when there isn’t enough room to show the view fully (for example, when the keyboard is up).

Our first attempt:

<ScrollView
    android:layout_width=...
    android:layout_width=...
    >
    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        />
</ScrollView>

Unfortunately there is a bug in Android where setting layout_gravity=”center” on a ScrollView’s child causes incorrect scrolling when you start hiding and showing other views in the layout (the ScrollView will get stuck with an offset such that you can’t completely scroll to the top, and you can scroll past the bottom).

Here’s the solution:

<ScrollView
    android:layout_width=...
    android:layout_width=...
    android:fillViewport="true"
    >
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        />
        <View
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            />
        <View
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            />
        <View
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            />
    </LinearLayout>
</ScrollView>

The wrap_content in the LinearLayout is a bit misleading: fillViewport=”true” in the ScrollView will cause its child to always be at least as large as the viewport. (See also Romain Guy’s article about fillViewport.)

Comments
  1. Tobias Alrøe says:

    There is a problem with your code.

    should be

  2. Benjamin R says:

    Thank you for sharing your solution.

  3. Octavian Ciubotaru says:

    Thanks!

  4. Gabriel says:

    LinearLayout shouldn’t be self-close in your code. But the rest is great!

    Sorry for my english.

Post a Comment

Your Information (Name required. Email address will not be displayed with comment.)

* Copy This Password *

* Type Or Paste Password Here *