ScrollView/NestedScrollView 无法填充满屏幕

2,272 阅读1分钟

ScrollView/NestedScrollView 滚动视图是指当拥有很多内容并且屏幕显示不完时,需要通过滚动来显示的视图。ScrollView/NestedScrollView 的一般用法如下:

以下代码在ScrollView/NestedScrollView 里面放了一个 RelativeLayout,并且通过设置高度为android:layout_height="match_parent" 来充满全屏的,RelativeLayout 里面放置了一个ImageView 并设置了一张图片。按照代码理解,图片的位置应该是居于屏幕中央的。代码如下:

<?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">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_gray_light">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:scaleType="centerCrop"
            android:src="@drawable/picture" />

    </RelativeLayout>

</ScrollView>

但是通过最后运行的效果,可以看到图片并没有居于整个屏幕的中央、而是在屏幕的最上面,如下图所示:


那么要怎么解决这个问题呢?最后发现 ScrollView/NestedScrollView 都有一个属性 android:fillViewport ,这个属性的作用就是指定此滚动视图是否应该拉伸其内容高度以填充视图,设置了这个属性就可以解决这个问题了。代码如下:

<?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:fillViewport="true">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@android:color/holo_gray_light">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:scaleType="centerCrop"
            android:src="@drawable/picture" />

    </RelativeLayout>

</ScrollView>

也就是说设置 ScrollView/NestedScrollView 的 android:fillViewport 为 true 即 android:fillViewport="true" 即可。

运行后的效果就正常了,如下图所示: