Place a block at the center of a ScrollView
Asked Answered
R

2

4

I have a ScrollView that contains a single child (elements wrapped by a LinearLayout). Sometime this child's height is half of the viewport's height, sometime it is bigger.

Here the layout :

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingRight="10dp"
    android:paddingBottom="10dp"
    android:paddingTop="10dp"
    android:background="@color/some_background">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:background="@drawable/fond_consult"
        android:orientation="vertical"
        android:weightSum="2">

        ... Some TextViews and ImageViews...

    </LinearLayout>
</ScrollView>

When the screen size and density is low, the child is correctly displayed in the ScrollView, but when rendering this activity on a bigger screen like HDPI and XHDPI, the content is placed at the top of the ScrollView.

Is there any way to set gravity for the sole child of the ScrollView, or do I have to delete the scrollView if the device screen is bigger than the measered height of the child ?

Rainout answered 29/8, 2012 at 12:36 Comment(2)
Try adding android:layout_gravity="center" to scrollview with its layout_width and layout_height as wrap_contentFrieder
thank you very much, It worked ! Could you post this as an answer so that I can accept it ?Rainout
F
14

What you can do is try adding android:layout_gravity="center" to ScrollView with its layout_width and layout_height as wrap_content. As ScrollView manages itself to the height and width of its child layouts.

Frieder answered 29/8, 2012 at 15:38 Comment(1)
Lol I searched multiple stackoverflow-questions for this problem and nobody mentioned a real solution, just the reason for it. Then there was you... :)Chagrin
T
1

In normal case, ScrollView will only occupy the minimum required space, so the question of vertical alignment(in case of vertical scroll) does not arise at all. You may go through the article in http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/. It may help you.

Transvalue answered 29/8, 2012 at 13:14 Comment(1)
the ScrollView with layout_height="match_parent" was occupying the whole space, but Lalit Poptani's comment was the trick I needed. Nevertheless, thank you for the link !Rainout

© 2022 - 2024 — McMap. All rights reserved.