I think a more elegant solution would be to use the ScrollView
's android:fillViewport
property. A ScrollView
is a little different in how it treats it's content view (can only have one), even if you set match_parent
(fill_parent
) to the ScrollView
it won't give that much spacing to it's content view, instead the default behavior is for the ScrollView
to wrap the content regardless of what you specify for that view. What android:fillViewport
does is tell the ScrollView
to stretch its content to fill the viewport (http://developer.android.com/reference/android/widget/ScrollView.html#attr_android:fillViewport). So in this case, your LinearLayout
would be stretched to match the viewport and if the height goes behind the viewport then it will be scrollable which is exactly what you want!
The accepted answer won't work properly when the content extends beyond the ScrollView
because it will still center the content view first causing it to cut off a portion of the view, and the ScrollView
centered in another layout works but just doesn't feel right, besides I think it will also result in a lint error (useless parent or something along those lines).
Try something like this:
<ScrollView
android:id="@+id/scroller"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="12dp"
android:paddingBottom="20dp"
android:scrollbarStyle="outsideOverlay"
android:fillViewport="true">
<LinearLayout
android:id="@+id/content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="check" />
</LinearLayout>
</ScrollView>
Just remember that the reason it is being centered here now is because of the android:gravity
on the LinearLayout
since the ScrollView
will stretch the LinearLayout
so keep that in mind depending on what you add to the layout.
Another good read on ScrollView
although not about centering but about fillViewport
is http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/