元素少时垂直居中滚动视图,元素多时垂直居中滚动视图

Center scrollview vertically when few elements and fill parent when many

当其中的元素很少时,我希望布局垂直居中,请参见左图。当元素很多的时候,我想让它变长,变成一个覆盖整个屏幕的滚动视图。见右图。

我怎样才能做到这一点?

红色元素是动态添加到布局中的。两个蓝色的 TextViews 在滚动视图之外。基本上,当屏幕上没有更多 space 时,滚动视图就会启动。

试试这个。

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#fff">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ff0000"
        android:gravity="center"
        android:padding="5dp"
        android:text="Top TextView"
        android:textColor="#fff" />

    <!-- You can remove min Height if you don't want it-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00ffff"
        android:minHeight="100dp">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <!-- Do you Code here.-->

        </ScrollView>
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:background="#ff0000"
        android:gravity="center"
        android:padding="5dp"
        android:text="Bottom TextView"
        android:textColor="#fff" />

</LinearLayout>