看一下下面这个布局在真机上跑起来之后的样子:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/red"
>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="@color/blue"/>
</LinearLayout>
</ScrollView>
有一点点不符合预期。预期是希望LinearLayout的height和width都是match_parent能充满整个ScrollView,但实际上看到的是LinearLayout的height是子内容的高度。
给ScrollView加上android:fillViewport="true"
这个属性之后,结果如下:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/red"
android:fillViewport="true"
>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:background="@color/blue"/>
</LinearLayout>
</ScrollView>
看一下官方文档上关于android:fillViewport
的说明:
Defines whether the scrollview should stretch its content to fill the viewport.
Must be a boolean value, either "true" or "false".
这个属性决定了是否要拉伸scrollview的内容来填满窗口。
ScrollView只支持上下滚动,仅在内容高度填不满整个屏幕的时候,android:fillViewport该属性才有效。当内容超过屏幕高度的时候,这个属性就可以不看了