ScrollView fillViewport 使用

1,862 阅读1分钟

ScrollView fillViewport 使用

有一个需求

  1. 界面中自上而下有两个方块,依次为A、B方块。
  2. A 方块的大小不固定,小的时候在屏幕内,大的时候会超过屏幕外。
  3. B 的布局,始终在A的下方,屏幕够显示时,在屏幕的最底部,屏幕不够显示时,随着A滑动。

fillViewport 引入

如果只在外层写了ScrollView,B会紧紧跟随A,B 不会始终在屏幕最底部了。 这时在 ScrollView 内加入 fillViewport=true, 就可以实现需求了。

效果图 与 layout 测试代码

1.png

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

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

            <TextView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@color/colorAccent"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:background="@color/colorPrimary"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintLeft_toLeftOf="parent"
                app:layout_constraintRight_toRightOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <RelativeLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:layout_width="100dp"
                    android:layout_height="200dp"
                    android:layout_alignParentBottom="true"
                    android:background="@mipmap/ic_launcher" />

            </RelativeLayout>

        </LinearLayout>

    </ScrollView>

</LinearLayout>